根据另一列的值显示列

时间:2011-04-12 06:10:13

标签: sql-server tsql

有一个这样的表:

Parent | Child
1      | 11
11     | 12
11     | 13
12     | 14
12     | 14

如果传递1,它应该返回所有'1'孩子的:11,12,13,14

2 个答案:

答案 0 :(得分:2)

您可以查看使用CTE的递归查询。 关于该主题的链接:

答案 1 :(得分:0)

-- Test data
declare @T table (ParentID int, ChildID int)
insert into @T values(1,       11)
insert into @T values(11,      12)
insert into @T values(11,      13)
insert into @T values(12,      14)
insert into @T values(12,      14)

-- ID to search for
declare @ParentID int = 1

-- Recorsive cte
;with cte as
(
  select T.*
  from @T as T
  where T.ParentID = @ParentID
  union all
  select T.*
  from cte as C
    inner join @T as T
      on C.ChildID = T.ParentID
)
select distinct ChildID
from cte  

结果

ChildID
-------
11
12
13
14