遞迴樹處理.

來源:互聯網
上載者:User

原貼:

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.