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

标签 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 的递归

谢谢

最佳答案

;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

关于tsql - 如何递归读取所有记录并按级别深度显示 TSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311080/

相关文章:

Jquery 太多递归错误

sql - 转义 SELECT 语句以将 a 存储在列中

tsql - 如何在SQL Server中生成Guid?

sql - 使用 T-SQL Merge 语句时如何避免插入重复记录

mysql - select count(*) 没有给出正确的计数

recursion - OCaml 中的递归类型?

python - 以递归方式存储返回值?

sql - 将 Access TRANSFORM/PIVOT 查询转换为 SQL Server

sql - oracle中给定数字之前最接近的数字

mysql - 从多个表中选择计数时,列名称不会更改