2015-01-05 123 views
0

我有一個分層表,其中爲每個孩子定義一個父母id(父母id爲空的頂級子女除外)。現在我想爲選定的孩子在一行中顯示每個父母身份。 我正在嘗試使用CTE,但CTE正在將其他記錄添加到初始設置中。取而代之的是我想與父母的名單更新初始集(SELECT語句選擇一些兒童)表的T-SQL如何在層次表中顯示所有父母id在一行(行)

例(表1):

ChildID ParentID 
A   P 
P   Q 
Q   Z 
B   P 
C   F 
F   M 
M   Q 
D   H 
H   Y 
Y   NULL 
Z   NULL 

如果最初的聲明將選擇C,A,Q從孩子們的ID,然後預期的結果列表如下:

Selected Child Parent ID's 
C     F, M, Q, Z 
A     P, Q, Z 
Q     Z  

回答

4

你是對的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); 
+0

你的做法是好的,你能添加一些解釋,只保留選擇部分(除去創建,插入等),所以它與出滾動屏幕適合酒吧。 – radar

+0

@radar你是對的,但沒有時間:) – Hatsjoem

+0

我喜歡與聲明的方法,因爲這是可以立即測試/驗證的東西。所以解決方案是使用FOR XML PATH來連接父母的記錄。這是我的解決方案 - 謝謝。 – phoenix

相關問題