--示例--示例数据
create table 原表(子节点 nvarchar(10),父节点 nvarchar(10),相对P001层 int,地址 nvarchar(10))
insert 原表 select 'A001','P001',1,'广州'
union  all  select 'A002','A001',2,'青岛'
union  all  select 'A003','A002',3,'广州'
union  all  select 'A004','A003',4,'广州'
union  all  select 'A005','A004',5,'上海'
union  all  select 'A006','A005',6,'广州'
go--查询的函数
create function f_qry(
@地址 nvarchar(10)
)returns @re table(子节点 nvarchar(10),父节点 nvarchar(10),重新排序后的层 int,地址 nvarchar(10))
as
begin 
declare @l int
declare @t table(id nvarchar(10),sid nvarchar(4000)) select @l=相对P001层  from 原表 where 父节点='P001'
insert @t select 子节点,子节点
from 原表 where 父节点='P001'
while @@rowcount>0
begin
set @l=@l+1
insert @t select a.子节点,b.sid+','+a.子节点
from 原表 a,@t b
where a.父节点=b.id and a.相对P001层=@l
end
insert @re select a.子节点,a.父节点,0,a.地址
from 原表 a,@t b
where a.子节点=b.id
order by b.sid set @l=0
update @re set @l=case 地址 when @地址 then @l+1 else @l end
,重新排序后的层=@l
return
end
go--调用函数实现查询
select * from f_qry(N'广州')
go--删除测试
drop table 原表
drop function f_qry/*--测试结果子节点        父节点        重新排序后的层     地址         
---------- ---------- ----------- ---------- 
A001       P001       1           广州
A002       A001       1           青岛
A003       A002       2           广州
A004       A003       3           广州
A005       A004       3           上海
A006       A005       4           广州
--*/

解决方案 »

  1.   


    --示例--示例数据
    create table 原表(子节点 nvarchar(10),父节点 nvarchar(10),地址 nvarchar(10))
    insert 原表 select 'A001','P001','广州'
    union  all  select 'A002','A001','青岛'
    union  all  select 'A003','A002','广州'
    union  all  select 'A004','A003','广州'
    union  all  select 'A005','A004','上海'
    union  all  select 'A006','A005','广州'
    go--查询的函数
    create function f_qry(
    @地址 nvarchar(10)
    )returns @re table(子节点 nvarchar(10),父节点 nvarchar(10),重新排序后的层 int,地址 nvarchar(10))
    as
    begin 
    declare @l int
    declare @t table(id nvarchar(10),sid nvarchar(4000),level int) set @l=0
    insert @t select 子节点,子节点,@l
    from 原表 where 父节点='P001'
    while @@rowcount>0
    begin
    set @l=@l+1
    insert @t select a.子节点,b.sid+','+a.子节点,@l
    from 原表 a,@t b
    where a.父节点=b.id and b.level=@l-1
    end
    insert @re select a.子节点,a.父节点,0,a.地址
    from 原表 a,@t b
    where a.子节点=b.id
    order by b.sid set @l=0
    update @re set @l=case 地址 when @地址 then @l+1 else @l end
    ,重新排序后的层=@l
    return
    end
    go--调用函数实现查询
    select * from f_qry(N'广州')
    go--删除测试
    drop table 原表
    drop function f_qry/*--测试结果子节点        父节点        重新排序后的层     地址         
    ---------- ---------- ----------- ---------- 
    A001       P001       1           广州
    A002       A001       1           青岛
    A003       A002       2           广州
    A004       A003       3           广州
    A005       A004       3           上海
    A006       A005       4           广州
    --*/