declare @Table1 table
(
ID varchar(2),
Name varchar(10),
PID varchar(2)
)
insert into @Table1 values
('A1', 'Apple', 'P1'),
('B1', 'Book', 'A1'),
('B2', 'Brook', 'A1'),
('C1', 'Cat', 'B1'),
('C2', 'Cook', 'B1'),
('C3', 'Car', 'B1'),
('D1', 'Dog', 'B2'),
('D2', 'Doll', 'B2'),
('E1', 'Egg', 'C1')
;with C as
(
select T.ID,
cast(T.Name as varchar(max)) as Name,
1 as Depth
from @Table1 as T
where T.Name = 'Apple'
union all
select T.ID,
cast(C.Name+'\'+T.Name as varchar(max)),
C.Depth + 1
from @Table1 as T
inner join C
on T.PID = C.ID
)
select C.ID,
C.Name,
C.Depth
from C
where C.Depth > 1
order by C.Name
Редактировать Без Apple.
;with C as
(
select T.ID,
cast(T.Name as varchar(max)) as Name,
1 as Depth
from @Table1 as T
inner join @Table1 as TP
on T.PID = TP.ID
where TP.Name = 'Apple'
union all
select T.ID,
cast(C.Name+'\'+T.Name as varchar(max)),
C.Depth + 1
from @Table1 as T
inner join C
on T.PID = C.ID
)
select C.ID,
C.Name,
C.Depth
from C
order by C.Name