Anda perlu menggunakan ekspresi tabel umum rekursif, lalu memfilter hasilnya hanya untuk jalur dasar untuk setiap record, (yaitu untuk ID 1131 dapatkan ABC/RST/UVW
dan bukan hanya 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;