2012-07-22 74 views
1

我有像父子關係數據庫表:SQL查詢的父子關係搜索和檢索所有節點和所有的父母

ID   Name   ParentID 
------------------------------------- 
1   Computer   0 
2   Software   1 
3   Hardware   1 
4   Windows   2 
5   Games    0 
6   Windows   5 
7   Linux    5 
8   3D    6 
9   DirectX   8 

我想在此表中搜索詞「窗口」和我想要的結果如下:

ID   Name   ParentID 
------------------------------------- 
1   Computer   0   <== Grandparent of 4 
2   Software   1   <== Parent of 4 
4   Windows   2   <== 4 
5   Games    0   <== Parent of 6 
6   Windows   5   <== 6 

我的意思是所有父母具有與搜索詞的關係應予以保留,而且其餘的應該從記錄中刪除

+0

解決方案也可以理解 – Mertez 2012-07-22 23:22:59

回答

2

您可以使用ASP.NET C#代碼Recursive CTE

with C as 
(
    select T.ID, T.Name, T.ParentID 
    from @T as T 
    where Name = 'Windows' 
    union all 
    select T.ID, T.Name, T.ParentID 
    from YourTable as T 
    inner join C 
     on T.ID = C.ParentID 
) 
select ID, Name, ParentID 
from C 
order by ID; 

SE-Data

+0

你的解決方案是真棒,謝謝。 – Mertez 2012-07-23 16:38:18

1

使用HierarchyId data type,然後使用方法

SELECT * FROM Table 
WHERE @searchId.IsDescendantOf(ID) = 1 

這使您可以執行任意的遞歸和/或循環的IsDescendant。這是快速和直接的。

+0

非常感謝你 – Mertez 2012-07-23 16:40:04