2014-03-26 19 views
2

我上拿表父子關係如何顯示父ID爲自己和孩子用T-SQL遞歸查詢

ID | ParentID | description 
1 | null | Company 
2 | 1 | Department 
3 | 2 | Unit1 
4 | 2 | Unit2 
5 | 4 | Unit3 
6 | 4 | Unit4 

,並假設顯示以下結果遞歸查詢的工作:

ID | ParentID | description 
1 | null | Company 
2 | 2 | Department 
3 | 2 | Unit1 
4 | 2 | Unit2 
5 | 2 | Unit3 
6 | 2 | Unit4 

當然,部件和單位的數量更大。基本任務是顯示parentId父級及其子級別。你有什麼想法如何實現這一目標?

到目前爲止,我只發此查詢

WITH cte (ID, ParentID, description) 
AS 
(
    SELECT ID, ParentID, description 
    FROM T1 
    UNION ALL 
    SELECT e.ID, e.ParentID, e.description 
    FROM T2 AS e 
    JOIN cte ON e.ID = cte.ParentID 

) 
SELECT 
cte.ID, cte.ParentID, cte.description 
FROM cte 
cte.ParentID is not null 
+0

試着把它放在SQL小提琴上。 –

回答

1

你的語法是不完全正確,但這個想法是在正確的方向。最後,你想獲取父母的父母爲NULL的行。這可能工作(它未經測試):

WITH cte(ID, ParentID, description, lev) AS 
     (SELECT ID, ParentID, description, 1 as lev 
     FROM table T1 
     UNION ALL 
     SELECT cte.ID, e.ParentID, cte.description, cte.lev + 1 
     FROM table e JOIN 
      cte 
      ON e.ID = cte.ParentID 
    ) 
SELECT cte.ID, cte.ParentID, cte.description 
FROM cte left outer join 
    table t 
    on cte.ParentId = t.ParentId  
WHERE t.ParentID is null; 
+0

不幸的是,查詢返回消息:語句終止。報表完成前,最大遞歸已耗盡。我已經將最大遞歸增加到32767,但沒有成功 – arth81

+0

Add:option(maxrecursion x)其中x是拋出異常之前想要允許的遞歸次數(缺省值爲100) –

+0

@ arth81。 。 。這可能表明你在使用的數據中有循環。 –