declare @source_id int
set @source_id=1
declare @age int
set @age=0
declare @t table(id int identity(1,1), c int, age int, order_f varbinary(8000), stub bigint)
insert @t(c, age, order_f, stub) values(@source_id, 0, cast(@source_id as binary(4)), null)
insert @t(c, age, order_f, stub) select baby_id, @age+1, b.order_f, 0
from relations_table as a inner join @t as b on b.c=a.parent and b.age=@age
inner join description_table as c on a.baby_id=c.id
order by c.description
while(@@ROWCOUNT>0)
begin
set @age=@age+1
update @t set order_f=order_f+cast(id as binary(4)), stub=null where age=@age
insert @t(c, age, order_f, stub) select baby_id, @age+1, b.order_f, 0
from relations_table as a inner join @t as b on b.c=a.parent and b.age=@age
inner join description_table as c on a.baby_id=c.id
order by c.description
end
select b.description
from @t as a inner join description_table as b on a.c=b.id
order by a.order_f |