2015-02-24 380 views
0

我有以下要求,層次結構在SQL Server - 多層次

輸入

ID Parent_ID 
------------ 
1 0 
2 0 
3 10 
4 0 
5 3 
6 20 
7 3 
8 21 
9 3 
10 0 
20 0 
21 0 
  • 當我使用@ID = 1結果必須是1
  • 當我使用@ID = 6結果必須是20.
  • 當我使用@ID = 5或7,9時,結果必須是10,因爲5 - > 3(Parent_ID - > Str_ID) - > 10(Parent_ID - > Str_I D) - > 0(在Parent_ID中停止爲0),所以結果爲10.

所以我的任務是查找ID,只要我在Parent_ID中找到0即可。

輸出:

@ID Result 
---------- 
1 1 
2 2 
3 10 
4 4 
5 10 
6 20 
7 10 
8 21 
9 10 
10 10 
20 20 
21 21 

回答

1

遞歸CTE與彙總可以這樣做:MSDN Article

BEGIN 
--Setup some data 
DECLARE @tmp as TABLE (ID int, ParentID int); 
INSERT INTO @tmp 
VALUES 
(1 , 0), 
(2 , 0), 
(3 , 10), 
(4 , 0), 
(5 , 3), 
(6 , 20), 
(7 , 3), 
(8 , 21), 
(9 , 3), 
(10, 0), 
(20, 0), 
(21, 0), 
(44, 5), 
(83, 44), 
(46, 83), 
(23, 7); 

WITH Parents (ID, ParentID, TopParent) AS (
    SELECT ID, ParentID, ID 
     FROM @tmp 
     WHERE ParentID = 0 
    UNION ALL 
    SELECT t.ID, t.ParentID, p.TopParent 
     FROM Parents p 
     JOIN @tmp t on t.ParentID = p.id) 
SELECT * FROM Parents 
--Or to get just the ID and top parent: SELECT ID, TopParent FROM Parents 

END 

結果:

ID   ParentID TopParent 
----------- ----------- ----------- 
1   0   1 
2   0   2 
4   0   4 
10   0   10 
20   0   20 
21   0   21 
8   21   21 
6   20   20 
3   10   10 
5   3   10 
7   3   10 
9   3   10 
23   7   10 
44   5   10 
83   44   10 
46   83   10