Du skal bruge et rekursivt fælles tabeludtryk og derefter filtrere resultaterne for kun basisstien for hver post, (dvs. for ID 1131 få ABC/RST/UVW
og ikke kun ABC/RST
WITH CTE AS
( SELECT ID,
Name,
ParentID,
NextParentID = ParentID,
Path = CAST(Name AS VARCHAR(MAX)),
Recursion = 1
FROM T
UNION ALL
SELECT CTE.ID,
CTE.Name,
CTE.ParentID,
T.ParentID,
CAST(T.Name + '/' + CTE.Path AS VARCHAR(MAX)),
Recursion + 1
FROM CTE
INNER JOIN T
ON CTE.NextParentID = T.ID
), CTE2 AS
( SELECT CTE.ID,
CTE.Name,
CTE.ParentID,
CTE.Path,
RowNumber = ROW_NUMBER() OVER(PARTITION BY CTE.ID ORDER BY Recursion DESC)
FROM CTE
)
SELECT ID, Name, ParentID, Path
FROM CTE2
WHERE RowNumber = 1;