Не ясно, пропускаете ли вы уровни в желаемых результатах, но похоже, что вы ищете рекурсивный CTE.Я уверен, что это совместимо с 2008 годом.
Пример
Declare @YourTable Table ([ID] int,[SubFolderOf] int,[FolderName] varchar(50))
Insert Into @YourTable Values
(1,0,'Main [ROOT]')
,(2,1,'Technical And Development')
,(3,1,'Sales and Marketing')
,(4,1,'Legal')
,(5,1,'Finance')
,(6,1,'Departments')
,(7,1,'Compliance')
,(8,2,'Test Scripts')
,(9,2,'Documentation')
,(10,2,'Files')
,(11,8,'AV Training')
,(12,8,'AV Finance 1')
Declare @Nest varchar(25) = '|-----' --<< Optional: Added for readability
;with cteP as (
Select Seq = cast(10000+Row_Number() over (Order by ID) as varchar(500))
,ID
,SubFolderOf
,Lvl=1
,FolderName
,Path = cast(FolderName as varchar(500))
From @YourTable
Where [SubFolderOf]=0
Union All
Select Seq = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.ID)) as varchar(500))
,r.ID
,r.SubFolderOf
,p.Lvl+1
,r.FolderName
,cast(p.path + ' >> '+r.FolderName as varchar(500))
From @YourTable r
Join cteP p on r.SubFolderOf = p.ID)
Select A.ID
,A.SubFolderOf
,A.Lvl
,FolderName = Replicate(@Nest,A.Lvl-1) + A.FolderName
,Path
From cteP A
Order By Seq
Возвращает