insert @temp(id)
select parent_id from a where id=@id and parent_id<>id
while exists(
select parent_id from a
where id in (select id from @temp)
and parent_id not in (select id from @temp)
)
insert @temp(id)
select parent_id from a
where id in (select id from @temp)
and parent_id not in (select id from @temp)