declare @relation table(ID int, LocationID int, ParentID int)
insert @relation values
(1,1,null),(2,2,1),(3,3,1),(4,4,2)
declare @Location table (LocationID int, LocationName varchar(3))
insert @Location values
(1,'L1'),(2,'L2'),(3,'L3'),(4,'L4'),(5,'L5'),(6,'L6')
;with a as
(
select ID p, ID, LocationID, ParentID from @relation where parentid is null
union all
select a.p, t.ID, t.LocationID, t.ParentID
from a join @relation t
on a.ID = t.ParentID
)
select L1.LocationID ParentID, L1.LocationName ParentName, L2.LocationID, L2.LocationName from a
join @Location L1
on a.p = L1.LocationID
join @Location L2
on a.id = L2.LocationID
option (maxrecursion 500)
结果:
ParentID ParentName LocationID LocationName
1 L1 1 L1
1 L1 2 L2
1 L1 3 L3
1 L1 4 L4