CTE返回层次结构中的所有项目

Pau*_*ing 2 sql-server recursive-query common-table-expression sql-server-2008

我有一个具有递归层次结构的表(即ID,ParentID)。对于这个层次结构中的任何项目,我希望能够带回上,下层次结构的所有列表以及每一行的级别。假设父母只能生一个孩子。

例如以下内容:

ID    ParentID
--------------
1     NULL
2     1
3     2
4     NULL
5     4
6     5
Run Code Online (Sandbox Code Playgroud)

给定ID 1、2或3,我想返回:

ID    ParentID    Level
-----------------------
1     NULL        1
2     1           2
3     2           3
Run Code Online (Sandbox Code Playgroud)

我以前做过,但是我不记得怎么做。我知道解决方案涉及CTE,但我做对了!任何帮助表示赞赏。

pod*_*ska 5

;with cte as 
(
    select *, 1 as level from @t where id = @yourid
    union all
    select t.*, level - 1
    from cte 
        inner join @t t on cte.parent = t.id
),
cte2 as
(   
    select * from cte
    union all
    select t.*, level+1
    from cte2 
        inner join @t t on cte2.id = t.parent

)
    select id,parent, ROW_NUMBER() over (order by level) level
    from (  select distinct id, parent, level from cte2) v
Run Code Online (Sandbox Code Playgroud)