SQL Server获取父列表

时间:2010-01-01 13:27:51

标签: sql-server hierarchy

我有一张这样的表:

id name parent_id
1  ab1  3
2  ab2  5
3  ab3  2
4  ab4  null
5  ab5  null
6  ab6  null

我需要使用输入id = 1进行查询(例如),结果将如下所示:

id name parent_id
5  ab5  null
2  ab2  5
3  ab3  2
1  ab1  3

(列出所有级别的所有父级,从项目id = 1开始)

2 个答案:

答案 0 :(得分:5)

或许这样的事情?

    WITH parents(id,name,parent,level)
    AS
    (
    SELECT
       ID,
       NAME,
       PARENT,
       0 as level
    FROM
       TABLE
    WHERE ID = 1
    UNION ALL
    SELECT
       ID,
       NAME,
       PARENT,
       Level + 1
    FROM 
       TABLE
    WHERE
       id = (SELECT TOP 1 parent FROM parents order by level desc)
    )
    SELECT * FROM parents

答案 1 :(得分:1)

使用WITH RECURSIVE。文档和适应性示例:Recursive Queries Using Common Table Expressions