Level
という列を追加する必要があります (またはあなたがそれを呼びたいものは何でも)-「アンカー」SELECTとCTEの再帰部分の両方に-次のように:
WITH CategoryRec AS
(
SELECT Id, Parentid, Name, 1 AS 'Level'
FROM dbo.Category
UNION ALL
SELECT cr.Id, c.Parentid, cr.Name, cr.Level + 1
FROM CategoryRec AS cr
INNER JOIN dbo.Category AS c ON cr.Parentid = c.Id
WHERE c.Parentid IS NOT NULL
)
SELECT DISTINCT Id, Parentid, Name, Level
FROM CategoryRec