原貼:
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