Похоже, вы можете использовать последовательность [CODE] в пути к иерархии
Пример
Declare @YourTable Table ([ID] int,[PARENT_ID] int,[CODE] varchar(50),[NAME] varchar(50))
Insert Into @YourTable Values
(218,NULL,1445,'First One')
,(235,218,2,'First Child')
,(247,235,45,'First Grandchild')
,(246,235,55,'Second Grandchild')
,(230,218,3,'Second Child')
,(238,230,12,'Third Grandchild')
,(231,230,20,'Fourth Grandchild')
;with cteP as (
Select ID
,PARENT_ID
,[Code]
,Name
,HierID = convert(hierarchyid,concat('/',[Code],'/'))
From @YourTable
Where Parent_ID is null
Union All
Select ID = r.ID
,PARENT_ID = r.PARENT_ID
,r.[Code]
,Name = r.Name
,HierID = convert(hierarchyid,concat(p.HierID.ToString(),r.[Code],'/'))
From @YourTable r
Join cteP p on r.PARENT_ID = p.ID)
Select Lvl = HierID.GetLevel()
,ID
,PARENT_ID
,[Code]
,Name
From cteP A
Order By A.HierID
Возвращает
Lvl ID PARENT_ID Code Name
1 218 NULL 1445 First One
2 235 218 2 First Child
3 247 235 45 First Grandchild
3 246 235 55 Second Grandchild
2 230 218 3 Second Child
3 238 230 12 Third Grandchild
3 231 230 20 Fourth Grandchild