Другой вариант - использовать hierachyid
тип данных
Пример
Declare @YourTable Table ([DepartmentId] int,[Parent_DepartmentId] int)
Insert Into @YourTable Values
(0,-1)
,(1,0)
,(2,1)
,(3,1)
,(4,0)
,(5,2)
,(6,5)
,(7,1)
;with cteP as (
Select DepartmentId
,Parent_DepartmentId
,HierID = convert(hierarchyid,concat('/',DepartmentId,'/'))
From @YourTable
Where Parent_DepartmentId =-1
Union All
Select DepartmentId = r.DepartmentId
,Parent_DepartmentId = r.Parent_DepartmentId
,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.DepartmentId,'/'))
From @YourTable r
Join cteP p on r.Parent_DepartmentId = p.DepartmentId)
Select Lvl = HierID.GetLevel()
,DepartmentId
,Parent_DepartmentId
,Path = HierID.ToString()
From cteP A
Order By A.HierID
Возвращает