下面是我的代码,从一个节点开始遍历所有节点:
SELECT * INTO MyTable
FROM
(
SELECT 1 Id, 1 ParentId, 'Parent A' Name
UNION ALL
SELECT 5,1,'Child A1'
UNION ALL
SELECT 47894,5,'Child A2'
UNION ALL
SELECT 2,2, 'Parent B'
UNION ALL
SELECT 3,2, 'Child B1'
)TAB
;With CTE as
(
select * from MyTable where Id = 47894
union all
select a.* from MyTable a inner join cte b
on a.Id=b.ParentId and a.Id<>b.Id
)
select STRING_AGG(Name, ' >> ') from CTE
输入47894时,它给出:
Child A2 >> Child A1 >> Parent A
如果我需要反向呢?
Parent A >> Child A1 >> Child A2
1条答案
按热度按时间fhg3lkii1#
您可以使用以下命令: