2013-10-12 66 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