你是對的CTE這樣做,但你必須採取所有的行,並把它們放到一列(見交叉應用 - XML路徑)。
with cte (selected, child, parent) as
(
select s.id, t.*
from @t as t
inner join @selected as s on t.childid = s.id
union all
select cte.selected, t.*
from @t as t
inner join cte on t.childid = cte.parent
where cte.parent is not null
)
select distinct
t.selected as [Selected Child],
left(a.parents,len(a.parents) - 1) as Parents
from cte t
cross apply (select cast(parent + ',' as text)
from cte tt
where t.selected = tt.selected
for xml path('')) a(parents);
樣本數據:
declare @t as table
(
childid char(1),
parentid char(1)
);
declare @selected as table
(
id char(1)
);
insert into @t (childid,parentid) values ('a','p'),
('p','q'),
('q','z'),
('b','p'),
('c','f'),
('f','m'),
('m','q'),
('d','h'),
('h','y'),
('y',null),
('z',null);
insert into @selected (id) values ('c'),('a'),('q');
with cte (selected, child, parent) as
(
select s.id, t.*
from @t as t
inner join @selected as s on t.childid = s.id
union all
select cte.selected, t.*
from @t as t
inner join cte on t.childid = cte.parent
where cte.parent is not null
)
select distinct
t.selected as [Selected Child],
left(a.parents,len(a.parents) - 1) as Parents
from cte t
cross apply (select cast(parent + ',' as text)
from cte tt
where t.selected = tt.selected
for xml path('')) a(parents);
你的做法是好的,你能添加一些解釋,只保留選擇部分(除去創建,插入等),所以它與出滾動屏幕適合酒吧。 – radar
@radar你是對的,但沒有時間:) – Hatsjoem
我喜歡與聲明的方法,因爲這是可以立即測試/驗證的東西。所以解決方案是使用FOR XML PATH來連接父母的記錄。這是我的解決方案 - 謝謝。 – phoenix