我有父子关系的db表,如:
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
我想在这张桌子上搜索“Windows”字样,我想要的结果如下:
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 :(得分:2)
您可以使用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;
答案 1 :(得分:1)
使用HierarchyId
data type,然后使用方法的IsDescendant
SELECT * FROM Table
WHERE @searchId.IsDescendantOf(ID) = 1
这允许您执行任意递归和/或循环。它快速而直接。