Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询,用于在父子关系中搜索并检索所有节点及其所有父节点_Sql_Sql Server_Tsql - Fatal编程技术网

SQL查询,用于在父子关系中搜索并检索所有节点及其所有父节点

SQL查询,用于在父子关系中搜索并检索所有节点及其所有父节点,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个具有父子关系的db表,如: ID Name ParentID ------------------------------------- 1 Computer 0 2 Software 1 3 Hardware 1 4 Windows 2 5 Games 0 6 W

我有一个具有父子关系的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
ID名称ParentID
-------------------------------------
1计算机0使用,然后使用方法的
IsDescendant

SELECT * FROM Table
WHERE @searchId.IsDescendantOf(ID) = 1
这允许您执行任意递归和/或循环。它快速而直接。

您可以使用


ASP.NET C代码中的解决方案也非常感谢您的解决方案非常棒,谢谢。
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;