使用一個CTE來定位樹的根,然後用第二CTE爆炸樹結構:
declare @T table (ID int not null, Parent int null)
insert into @T(ID,Parent) values
(1, NULL),
(2, 1 ),
(3, 2 ),
(4, 2 ),
(5, NULL),
(6, 5 ),
(7, NULL)
declare @Node int
set @node = 3
;With Root as (
select t.ID,t.Parent from @T t where t.ID = @Node or t.Parent = @Node
union all
select t.ID,t.Parent
from
Root r
inner join
@t t
on
t.ID = r.Parent
), Tree as (
select ID,Parent from Root where Parent is null
union all
select t.ID,t.Parent
from @T t
inner join
Tree tr
on tr.ID = t.Parent
)
select * from Tree
結果:
ID Parent
----------- -----------
1 NULL
2 1
3 2
4 2
希望你可以看到兩個CTE正在朝相反的方向工作。