I made use of a table variable for the sake of demonstration. To use a standard table, remove the @tempTable
declaration and insert statements. Then replace the @tempTable
references with the table name.
declare @childId int
set @childId = 184
declare @tempTable table(parent int, child int)
insert into @tempTable values(190, 192)
insert into @tempTable values(192, 180)
insert into @tempTable values(180, 185)
insert into @tempTable values(185, 184)
insert into @tempTable values(190, 191)
insert into @tempTable values(191, 197)
insert into @tempTable values(197, 200)
declare @currentItem int
set @currentItem = @childId
declare @output varchar(max)
set @output = cast(@currentItem as varchar)
while (exists(select 1 from @tempTable where child = @currentItem))
begin
select
@currentItem = parent
from
@tempTable
where
child = @currentItem
set @output = cast(@currentItem as varchar) + ', ' + @output
end
select @output
Some example output:
For 184: 190, 192, 180, 165, 184
For 200: 190, 191, 197, 200