DECLARE @
FileTreeId
INT = 300 (For instance) ;WITH FileTreeHierarchy AS
( SELECT FileTreeID, Company, Parent, Name, 1 AS 'Level' FROM FileTree WHERE FileTreeID = @FileTreeId UNION ALL SELECT
F
.FileTreeID,
F
.Company,
F
.Parent,
F
.Name,
FH.Level + 1 AS 'Level' FROM FileTree F INNER JOIN FileTreeHierarchy
FH
ON
FH
.Parent =
F
.FileTreeID
)
SELECT FileTreeId, Company CompanyId, Parent, Name,
[Level] = CAST([Level] as int)
FROM FileTreeHierarchy Order By [Level] Desc