I found myself having an eerily similar issue, except that I am not using MS SQL at all! But with MariaDB.
Fortunately a solution was found inspired by @Oleksandr . I of course found this question through google, but in case anyone else has this specific problem and they happen to use MariaDB, fear not.
SqlFiddle
WITH RECURSIVE MyTree AS (
SELECT NULL AS ParentCategoryId, 'A' AS ChildCategoryId UNION ALL
SELECT 'A', 'C' UNION ALL
SELECT 'A', 'B' UNION ALL
SELECT 'A', 'D' UNION ALL
SELECT 'B', 'E' UNION ALL
SELECT 'E', 'C' UNION ALL
SELECT 'D', 'C'
),
CTE AS (
-- Anchor member: select leaf nodes
SELECT
ChildCategoryId AS Node,
ParentCategoryId AS Parent,
CAST(ChildCategoryId AS CHAR(100)) AS NodePath,
1 AS Level
FROM MyTree
WHERE ChildCategoryId NOT IN (SELECT DISTINCT ParentCategoryId FROM MyTree WHERE ParentCategoryId IS NOT NULL)
UNION ALL
-- Recursive member: join to previous results and extend the path
SELECT
CTE.Node,
mt.ParentCategoryId AS Parent,
CONCAT(mt.ChildCategoryId, ' > ', CTE.NodePath) AS NodePath,
Level + 1 AS Level
FROM CTE
JOIN MyTree mt ON CTE.Parent = mt.ChildCategoryId
)
-- Final SELECT for the recursive CTE to return results without NULL Parents
SELECT DISTINCT
TRIM(TRAILING ' > ' FROM NodePath) AS 'FullPath'
FROM CTE
WHERE Parent IS NULL
ORDER BY Level DESC;
connect by
andstart with
operators, and as far as I know the newer versions of SQLServer already have most of the features that Oracle has – Footling