2012-07-22 72 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