Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Concatenação recursiva de elementos pai


Você pode usar um CTE recursivo .
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;