declare @t table (id int, parent int)
insert @t (id, parent)
SELECT EmployeeID,ReportsTo
FROM NORTHWIND..Employees
; with cte as (
select id, parent
, cast(RIGHT(REPLICATE(' ',12) +
CONVERT(varchar(12),id),12) as varchar(max)) Path
from @t
where parent is null
union all
select child.id, child.parent
, parent.Path + RIGHT(REPLICATE(' ',12) +
CONVERT(varchar(12),child.id),12) as Path
from @t child
join cte parent
on parent.id = child.parent
)
select *
from cte
order by Path