How to read all records recursively and show by level depth TSQL

爷,独闯天下 提交于 2020-01-04 02:46:07

问题


Is there a way to read records recursively in similar table and order by depth level?

#table:

id int    |   parent int    |   value string
--------------------------------------------
1             -1                some
2             1                 some2
3             2                 some3
4             2                 some4
5             3                 some5
6             4                 some6
7             3                 some5
8             3                 some5
9             8                 some5
10            8                 some5

So is there a way to recursively select where result table would look like this.

select * from #table where id=3 

id int      | parent int      | value string   |  depth  
--------------------------------------------------------
3             2                 some3             0
5             3                 some5             1
7             3                 some5             1 
8             3                 some5             1
9             8                 some5             2
10            8                 some5             2

So if I choose id=3 I would see recursion for id=3 and children

Thank you


回答1:


;with C as
(
  select id,
         parent,
         value,
         0 as depth
  from YourTable
  where id = 3
  union all
  select T.id,
         T.parent,
         T.value,
         C.depth + 1
  from YourTable as T
    inner join C  
      on T.parent = C.id
)
select *
from C

SE-Data




回答2:


You can accomplish using CTEs, in particular rCTEs.

See this, and this for more information.

Example to follow:

WITH sampleCTE (id, parent, value, depth)
    AS (
        -- Anchor definition
        SELECT id
            , parent
            , value
            , 0
        FROM #table
        WHERE id = @targetId
        -- Recursive definition
        UNION ALL
        SELECT child.id
            , child.parent
            , child.value
            , sampleCTE.depth + 1
        FROM #table child 
            INNER JOIN sampleCTE ON sampleCTE.id = child.parent
    )


来源:https://stackoverflow.com/questions/10311080/how-to-read-all-records-recursively-and-show-by-level-depth-tsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!