2013-12-23 24 views
1

我有一個包含ID和ParentID的表。我需要找到給定記錄的所有相關子記錄。SQL:給定一條記錄,如何在不知道層次結構中的層次數的情況下查找其所有關聯的子記錄?

SQL FIddle Example

給出ID = '005'

Create table #Temp 
(
    ID varchar(10) 
    ,ParentID varchar(10) 
    ,Name varchar(20) 
) 

Insert into #Temp 
    values 
    ('001','002','a') 
    ,('002','003','b') 
    ,('003',NULL,'c') 
    ,('004','003','d') 
    ,('005','002','e') 
    ,('006','005','f') 
    ,('007','008','g') 
    ,('008','006','h') 
    ,('009','005','i') 
    ,('010','009','j') 
    ,('011','005','k') 
    ,('012','010','l') 
    ,('013','010','m') 

例如,我想找到它的所有子記錄。

Results would be ID 006,008,009,010,011,012,013 

任何想法表示讚賞。

+0

你可以做它與[遞歸cte](http://technet.microsoft.com/en-us/library/ms186243.aspx) – Blorgbeard

+0

請注意,007應在您的答案,因爲007 - > 008 - > 006 - - > 005。 –

回答

1

這裏是它給你的答案遞歸CTE的例子:

; with cte as (

    select ID, parentid, name from temp where parentid = '005' 

    union all 

    select t.ID, t.parentid, t.name from temp t 
    join cte c on c.id=t.parentid 
) 

select * from cte 

見琴:http://sqlfiddle.com/#!6/0e74d/4

1

這需要一個遞歸CTE。假設你的數據確實是一棵樹,沒有周期:

with cte as (
     select id, parentid 
     from #Temp 
     where parentid = '005' 
     union all 
     select child.id, cte.id 
     from cte join 
      #Temp child 
      on cte.id = child.parentid 
    ) 
select distinct id 
from cte; 
相關問題