开发者

Get entire chain of IDs in self-referencing table given any ID in hierachy

开发者 https://www.devze.com 2023-03-12 20:34 出处:网络
I have a table that contains the following data: +--开发者_JS百科--+----------+ ID | ParentID | +----+----------+

I have a table that contains the following data:

+--开发者_JS百科--+----------+
| ID | ParentID |
+----+----------+
| 27 |    0     |
| 38 |    27    | 
| 45 |    38    |
| 86 |    0     |
| 92 |    45    |
| 48 |    86    |
| 62 |    92    |
| 50 |    62    |
-----------------

I would like to be able to pass any ID to a stored procedure and get the entire chain of IDs (parents and children) of that given ID.

ie. if I pass ID = 45, I should get:

27
38
45
92
62
50

Similarly, if I pass ID = 86, I should get:

86
48

Any help would be greatly appreciated!


You can use two recursive CTE's. The first finds the root node and the second builds the chain.

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

Version 2

A bit shorter and query plan suggests more effective but you never know without testing on real data.

;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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号