如何递归读取所有记录并按级别深度TSQL显示

时间:2012-04-25 07:19:42

标签: tsql select recursion

有没有办法在类似的表中递归读取记录并按深度级别排序?

#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

那么有没有办法递归选择结果表的位置。

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

因此,如果我选择id = 3,我会看到id = 3和children

的递归

谢谢

2 个答案:

答案 0 :(得分:5)

;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

答案 1 :(得分:3)

您可以使用CTE完成,特别是rCTE。

有关详细信息,请参阅thisthis

要遵循的示例:

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
    )