在给定层次结构中的任何ID的情况下,在自引用表中获取整个ID链

时间:2011-06-11 21:47:31

标签: recursion parent-child hierarchy sql-server-2008-r2 common-table-expression

我有一个包含以下数据的表:

+----+----------+
| ID | ParentID |
+----+----------+
| 27 |    0     |
| 38 |    27    | 
| 45 |    38    |
| 86 |    0     |
| 92 |    45    |
| 48 |    86    |
| 62 |    92    |
| 50 |    62    |
-----------------

我希望能够将 任何 ID传递给存储过程并获取 整个 链给定身份证的身份证(父母和子女)。

即。如果我通过ID = 45,我应该得到:

27
38
45
92
62
50

同样,如果我传递ID = 86,我应该得到:

86
48

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用两个递归CTE。第一个找到根节点,第二个构建链。

declare @T table(ID int, ParentID int)

insert into @T values (27,  0), (38, 27), (45, 38), (86,  0),
                      (92, 45), (48, 86), (62, 92), (50, 62)    

declare @ID int = 45

;with cte1 as
(
  select T.ID, T.ParentID, 1 as lvl
  from @T as T
  where T.ID = @ID
  union all
  select T.ID, T.ParentID, C.lvl+1
  from @T as T
    inner join cte1 as C
      on T.ID = C.ParentID
),
cte2 as
(
  select T.ID, T.ParentID
  from @T as T
  where T.ID = (select top 1 ID
                from cte1
                order by lvl desc)
  union all
  select T.ID, T.ParentID
  from @T as T
    inner join cte2 as C
      on T.ParentID = C.ID
)
select ID
from cte2

版本2

稍微短一点,查询计划表明更有效,但如果不对实际数据进行测试,你就永远不会知道。

;with cte as
(
  select T.ID, T.ParentID, ','+cast(@ID as varchar(max)) as IDs
  from @T as T
  where T.ID = @ID
  union all
  select T.ID, T.ParentID, C.IDs+','+cast(T.ID as varchar(10))
  from @T as T
    inner join cte as C
      on (T.ID = C.ParentID or
          T.ParentID = C.ID) and
          C.IDs+',' not like '%,'+cast(T.ID as varchar(10))+',%'
)
select ID
from cte