2013-10-12 69 views
0

MSSQL 我有T1表格,Idname列。像上一個問題一樣,但還有另一項任務。嵌套表格元素查詢

T2Aggregate_IDElement_ID

他們越過

X1:

ID и Name 

1 Car 
2 Hood 
3 Engine 
4 Cylinder 
5 Wheel 
6 tyre 
7 rim (car) 
8 Rim fixation (Car) 

X2:

Aggregate_ID Element_ID 

1 2 
1 3 
1 5 
3 4 
5 6 
5 7 
7 8 

我需要輸出的所有元素簡單,其中包括總狀輪。在輪子的情況下將是6,8。 要「汽車」它將是2,4,6,8 嵌套級別可以更改。這是一個簡單的例子。但嵌套層次可以是4,5..20或無限制。

我讀這http://technet.microsoft.com/ru-ru/library/ms186243(v=sql.105).aspx但現在我不能老是處理它

回答

1

您可以使用下面的查詢。它使用公用表表達式。第一部分獲取作爲參數的聚合。第二部分遞歸添加下一個聚合。

然後我選擇那些樹的樹葉(不是父母)的集合。

declare @part as varchar(max) = 'wheel' 

;with cte 
as 
(

    select aggregate_id, element_id 
    from t2 where aggregate_id = (select id from t1 where name = @part) 

    union all 

    select t2.aggregate_id, t2.element_id 
    from t2 
    inner join cte on cte.element_id = t2.aggregate_id 
) 

select distinct c1.element_id from cte c1 
where not exists (select * from cte c2 where c1.element_id = c2.aggregate_id) 
+0

謝謝。我會學習。我怎樣才能做到沒有遞歸?循環? – ifooi