想象一个如下表:
表:人
字段: ID、FullName、ParentID
ParentID 再次引用 Person 表中的 ID。
问题: 对于上面给出的示例,我如何在 TSQL 中查询以找到 ID = 7 的 Person 的最高父级?
想象一个如下表:
表:人
字段: ID、FullName、ParentID
ParentID 再次引用 Person 表中的 ID。
问题: 对于上面给出的示例,我如何在 TSQL 中查询以找到 ID = 7 的 Person 的最高父级?
您将使用公用表表达式并执行递归查询,直到找到最顶层的父项,如下所示:
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 TOP 1 id FROM parent
order by id asc
DROP TABLE #tmp
如果想测试那个查询应该没问题!
WITH abcd
AS (
-- anchor
SELECT id, FullName, ParentID,
FullName AS "Path"
FROM Person
WHERE ParentId IS NULL
UNION ALL
--recursive member
SELECT p.id, p.FullName, p.ParentID,
CAST((a.path + '/' + p.FullName) AS VARCHAR(1000)) AS "Path"
FROM Person AS p
JOIN abcd AS a
ON p.ParentId = a.id
)
SELECT * FROM abcd