Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Concatenation of Parent Elements

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.

like image 675
Greg Avatar asked Feb 02 '12 05:02

Greg


2 Answers

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;     
like image 106
Mikael Eriksson Avatar answered Nov 16 '22 00:11

Mikael Eriksson


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

like image 3
Pam Lahoud Avatar answered Nov 16 '22 01:11

Pam Lahoud