The following is the i-th answer, modified in the Royi Namir query, to use left numbered number strings for the path:
;WITH CTE AS( SELECT childID, parentID, 0 AS depth, NAME , location, Cast( Right( '00000' + Cast( Location as VarChar(6) ), 6 ) as VarChar(1024) ) as Path FROM @myTable WHERE childID = parentID UNION ALL SELECT TBL.childID, TBL.parentID, CTE.depth + 1 , TBL.name ,TBL.location, Cast( cte.Path + '.' + Right( '00000' + Cast( Tbl.Location as VarChar(6) ), 6 ) as VarChar(1024) ) FROM @myTable AS TBL INNER JOIN CTE ON TBL.parentID = CTE.childID WHERE TBL.childID<>TBL.parentID ) SELECT depth, childID, parentID, location, REPLICATE('----', depth) + name FROM CTE ORDER BY path
NB: not completed and written on vacation.
Separators ( . ) Are not required, but simplify the reading of the resulting values ββand may simplify some operations, for example. finding common paths.
source share