Here is an old sample I had saved off. It includes code to avoid circular references as well. You should be able to adapt it to your table as it is based on hierarchal structure of id/parentid:EDIT:Recursive CTE is a good way to handle parent/child solutions but avoiding circular references was a problem (for me anyway). I'm pretty sure this solution was inspired by PESO. It may even be his code I don't remember :)DECLARE @Sample TABLE ( PageID INT, ParentID INT )INSERT @SampleSELECT 46, 18 UNION ALLSELECT 5, 46 UNION ALLSELECT 6, 5 UNION ALLSELECT 7, 6 UNION ALLselect 46, 7 union all --circular referenceSELECT 8, 6 UNION ALLSELECT 9, 6 UNION ALLSELECT 10, 6 UNION ALLSELECT 11, 6 UNION ALLSELECT 12, 6 UNION ALLSELECT 13, 6 UNION ALLSELECT 14, 6 ;WITH Yak(PageID, parentid, p, [pi])AS ( SELECT s.PageID, 0, replace(convert(varchar(max), str(s.pageid,3)),' ','0'), convert(bigint,0) FROM @Sample s left outer join @sample x on x.pageid = s.parentid where x.pageid is null UNION ALL SELECT s.PageID, y.pageid, replace(y.p + '-' + str(s.pageid,3),' ','0'), patindex( '%' + replace(str(s.pageid,3),' ','0') + '%', y.p) FROM Yak AS y INNER JOIN @Sample AS s ON s.ParentID = y.PageID where patindex( '%' + replace(str(s.pageid,3),' ','0') + '%', y.p) = 0)SELECT PageID, parentid, p as [structure] --, [pi]FROM Yakoption (maxrecursion 10)OUTPUT:PageID parentid structure----------- ----------- ------------------46 0 0465 46 046-0056 5 046-005-0067 6 046-005-006-0078 6 046-005-006-0089 6 046-005-006-00910 6 046-005-006-01011 6 046-005-006-01112 6 046-005-006-01213 6 046-005-006-01314 6 046-005-006-014
Be One with the OptimizerTG