A CTE подойдет для решения этой проблемы.Хитрость заключается в том, чтобы сохранить root
ID при выполнении CTE.
Оператор SQL
;WITH q AS (
SELECT root = catID, catID, catFatherID
FROM tblCategories
UNION ALL
SELECT q.root, c.catID, c.catFatherID
FROM q
INNER JOIN tblCategories c ON c.catFatherID = q.catID
)
SELECT root, catID
FROM q
ORDER BY
root, catID
Тестовый скрипт
;WITH tblCategories (catID, catFatherID) AS (
SELECT 1, NULL
UNION ALL SELECT 2, 1
UNION ALL SELECT 3, 1
UNION ALL SELECT 4, 2
UNION ALL SELECT 5, 3
UNION ALL SELECT 6, 4
)
, q AS (
SELECT root = catID, catID, catFatherID
FROM tblCategories
UNION ALL
SELECT q.root, c.catID, c.catFatherID
FROM q
INNER JOIN tblCategories c ON c.catFatherID = q.catID
)
SELECT root, catID
FROM q
ORDER BY
root, catID