cte, . SEQUENCE, row_numbers ( ) Priority.
Declare @YourTable Table ([Id] varchar(50),[__ParentId] varchar(50),[Priority] varchar(50))
Insert Into @YourTable Values
(1,NULL,NULL)
,(2,1,100)
,(3,1,300)
,(4,1,200)
,(5,4,100)
,(6,4,200)
,(7,6,100)
,(8,5,100)
,(9,5,200)
,(10,9,100)
,(11,5,50)
Declare @Top int = null
Declare @Nest varchar(25) = '|-----'
;with cteP as (
Select Seq = cast(10000+Row_Number() over (Order by [Priority]) as varchar(500))
,ID
,__ParentId
,Lvl=1
,Priority
From @YourTable
Where IsNull(@Top,-1) = case when @Top is null then isnull(__ParentId ,-1) else ID end
Union All
Select Seq = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.[Priority])) as varchar(500))
,r.ID
,r.__ParentId
,p.Lvl+1
,r.Priority
From @YourTable r
Join cteP p on r.__ParentId = p.ID)
Select A.ID
,A.__ParentId
,A.Lvl
,A.Priority
,Name = Replicate(@Nest,A.Lvl-1) +cast(ID as varchar(25))
From cteP A
Order By Seq
