Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Concaténation récursive des éléments parents

Vous pouvez utiliser un CTE récursif .

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;