create table #yourtable(
childid int
,parentid int
);
insert into #yourtable(childid,parentid)
values (1,1)
,(2,1)
,(5,1)
,(4,5)
,(3,2)
,(6,6)
,(9,6)
,(7,9)
,(8,7)
;
alter table #yourtable
add rootid int
;
update t1
set t1.rootid=isnull(t2.parentid,t1.parentid)
from #yourtable as t1
left outer join #yourtable as t2
on t2.childid=t1.parentid
and t2.childid<>t2.parentid
;
while (@@rowcount>0)
begin
update t1
set t1.rootid=t2.parentid
from #yourtable as t1
inner join #yourtable as t2
on t2.childid=t1.rootid
and t2.childid<>t2.parentid
;
end;
select * from #yourtable;
drop table #yourtable;