如何在表中找到代表层次结构的最顶层记录(在TSQL中)?

时间:2012-12-17 08:42:20

标签: sql sql-server tsql hierarchy

想象一下如下表:

表:

字段: ID,FullName,ParentID

其中ParentID再次引用Person表中的ID。

问题: 对于上面给出的示例,如何在TSQL中查询以找到ID = 7的Person的最顶级Parent?

2 个答案:

答案 0 :(得分:3)

您将使用公用表表达式并执行递归查询,直到找到最顶层的父表达式为止:

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

答案 1 :(得分:2)

如果想测试该查询,那应该没问题!

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