我有以下要求,
输入
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_ID) - > 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
答案 0 :(得分: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