Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Rekursive Verkettung von Elternelementen

Sie können einen rekursiven CTE verwenden .

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;