原贴:
http://community.csdn.net/Expert/topic/4536/4536413.xml?temp=.2449457
表中有两个字段:
子 父
A null
B A
C B
D C
E C
我的目的是:怎样根据一个父级条件,就把包括父级在内的所有子级查询出来?
比如:
父级条件是“B”,结果应该是:
子 父
B A
C B
D C
E C
父级条件是“C”,结果应该是:
子 父
C B
D C
E C
注意:子级数没有限制,可以任意有任意数目的子级。
--测试环境
Create table Test(子 varchar(10),父 varchar(10))
insert into Test select 'A',NULL
union all select 'B','A'
union all select 'C','B'
union all select 'D','C'
union All select 'E','C'
--建函数
CREATE Function F_Tree(@父 varchar(10))
returns @t table(子 varchar(10),父 varchar(10),level int)
begin
declare @i int
set @i=1
insert @t select *,@i from Test where 子=@父
while @@rowcount<>0
begin
set @i=@i+1
insert @t select a.*,@i from Test a,@t b
where b.子=a.父 and b.level=@i-1
end
return
end
--查询
select 子,父 from dbo.F_Tree('B')
select 子,父 from dbo.F_Tree('C')
--结果
子 父
---------- ----------
B A
C B
D C
E C
(4 row(s) affected)
子 父
---------- ----------
C B
D C
E C
(3 row(s) affected)
--删除环境
Drop table Test
Drop function F_Tree