select myself,father from dbo.getsubtreeinfo('a') where myself<>'a'
-------------------------------------------------------------------
myself father
b a
b1 a
b2 a
c b
c1 b
d c
create table getchild
(
myself varchar(100),
father varchar(100)
)
insert into getchild
select 'a' , NULL union all
select 'b' , 'a' union all
select 'b1' , 'a' union all
select 'b2' , 'a' union all
select 'c' , 'b' union all
select 'c1' , 'b' union all
select 'd' , 'c'
create function dbo.getSubtreeInfo
(
@father as varchar(100)
)
returns @treeinfo table
(
myself varchar(100),
father varchar(100),
level int
)
begin
declare @level as int
select @level=0
insert into @treeinfo
select myself,father,@level from getchild where myself=@father
while @@rowcount>0
begin
set @level=@level+1
insert into @treeinfo
select e.myself,e.father,@level from getchild as e join @treeinfo as t
on e.father=t.myself and t.level=@level-1
end
return
end
declare @s varchar(1000)
set @s=' '
select @s=@s+ myself+',' from dbo.getsubtreeinfo('a') where myself<>'a'
print left(@s,len(@s)-1)
-----------------------------------
b,b1,b2,c,c1,d