Mic*_*ner 2 sql t-sql sql-server ssms parent-child
摘要
在Azure数据库中(使用SQL Server Management Studio 17,所以使用T-SQL),我试图连接多个不同长度的父子关系。
基本表
我的桌子是这样的:
ID parent
1 2
2 NULL
3 2
4 3
5 NULL
Run Code Online (Sandbox Code Playgroud)
随意使用以下代码来生成并填充它:
DECLARE @t TABLE (
ID int,
parent int
)
INSERT @t VALUES
( 1, 2 ),
( 2, NULL ),
( 3, 2 ),
( 4, 3 ),
( 5, NULL )
Run Code Online (Sandbox Code Playgroud)
问题
如何收到具有路径串联的表,如下表所示?
ID path parentcount
1 2->1 1
2 2 0
3 2->3 1
4 2->3->4 2
5 5 0
Run Code Online (Sandbox Code Playgroud)
详情
实际表中的行更多,最长的路径应包含〜15个ID。因此,找到在母体计数定义方面动态的解决方案将是理想的。另外:我不必一定要使用“ parentcount”列,因此可以在回答中略过它。
select @@version:
Microsoft SQL Azure (RTM) - 12.0.2000.8
Run Code Online (Sandbox Code Playgroud)
您可以为此使用递归CTE:
with cte as (
select id, parent, convert(varchar(max), concat(id, '')) as path, 0 as parentcount
from @t t
union all
select cte.id, t.parent, convert(varchar(max), concat(t.id, '->', path)), parentcount + 1
from cte join
@t t
on cte.parent = t.id
)
select top (1) with ties *
from cte
order by row_number() over (partition by id order by parentcount desc);
Run Code Online (Sandbox Code Playgroud)