Recursive Concatenation of Parent Elements

2020-06-04 10:47发布

问题:

I have a table that looks like this:

ID     |Name    |Parent
1      |A       |NULL
2      |B       |NULL
3      |C       |1
4      |D       |1
5      |E       |3
6      |F       |5

I would like to have a view return this:

ID     |Name    |ParentNames
1      |A       |
2      |B       |
3      |C       |A
4      |D       |A
5      |E       |A > C
6      |F       |A > C > E

I tried to left join a view showing an IDs first parent and left joining it with itself but that didn't work.

Is there a way to do this without a stored procedure/function? I've got ~15k rows with ~0-5 parents each but I'd rather not hard code a maximum of 5 parents.

回答1:

You can use a recursive CTE.

declare @T table(ID int, Name char(1), Parent int);

insert into @T values  
(1      ,'A'       ,NULL),
(2      ,'B'       ,NULL),
(3      ,'C'       ,1),
(4      ,'D'       ,1),
(5      ,'E'       ,3),
(6      ,'F'       ,5);

with C as
(
  select ID,
         Name,
         Parent,
         cast('' as varchar(max)) as ParentNames
  from @T
  where parent is null
  union all
  select T.ID,
         T.Name,
         T.Parent,
         C.ParentNames + ' > ' + C.Name
  from @T as T         
    inner join C
      on C.ID = T.Parent
)      
select ID,
       Name,
       stuff(ParentNames, 1, 3, '') as ParentNames
from C;     


回答2:

Not sure if this is a possibility for you, but have you looked into the new hierarchy ID?

http://msdn.microsoft.com/en-us/library/bb677290.aspx