walking UP the tree is very similar to walking DOWN the tree. It is just a matter of tweaking JOIN correlation with id and parentid.and just returning the ultimate parent means just returning the top 1 row in desc order. If this doesn't work for you then post executable DDL/DML and your expected results.declare @h table (id int, parentid int NULL)insert @h select 10, 5 union allselect 9, 5 union allselect 8, 5 union allselect 7, 5 union allselect 6, 5 union allselect 5, 3 union allselect 4, 3 union allselect 3, 1 union allselect 2, 1 union allselect 1, nulldeclare @start intset @start = 10;with cte (id, parentid, lev)as ( select id, parentid, 1 from @h where id = @start union all select h.id, h.parentid, c.lev + 1 from cte c join @h h on h.id = c.parentid)select top 1 id [ultimate parent]from cte order by lev descOUTPUT:ultimate parent---------------1
Be One with the OptimizerTG