我想知道是否有人可以帮助我。
我有一张像这样的桌子......
ID ParentID
1 0
2 1
3 2
4 3
5 4
我想要做的是写一个递归的TSQL语句,它将获取我父亲的所有ID。因此,例如,如果我将5传递给存储过程,它将返回4,3,2,1。
有谁知道怎么做?如果有人可以提供帮助,我们将非常感激!
答案 0 :(得分:2)
这是一个如何使用递归CTE实现此目的的示例:
DECLARE @id INT
SET @id = 5
CREATE TABLE #tmp (id INT , ParentId INT)
INSERT INTO #tmp VALUES(1,0)
INSERT INTO #tmp VALUES(2,1)
INSERT INTO #tmp VALUES(3,2);
INSERT INTO #tmp VALUES(4, 3);
INSERT INTO #tmp VALUES(5,4);
WITH parent AS
(
SELECT id, parentId from #tmp WHERE id = @id
UNION ALL
SELECT t.id, t.parentId FROM parent
INNER JOIN #tmp t ON t.id = parent.parentid
)
SELECT id FROM parent
WHERE id <> @id;
- OR
WITH parent AS
(
SELECT tmp1.id, tmp1.parentId from #tmp AS tmp1
INNER JOIN #tmp AS tmp2 ON tmp1.id = tmp2.parentId
WHERE tmp2.id = @id
UNION ALL
SELECT t.id, t.parentId FROM parent
INNER JOIN #tmp t ON t.id = parent.parentid
)
SELECT id FROM parent
答案 1 :(得分:0)