Trying to write a recursive CTE query, keep getting the following error: level, invalid column name
This is the query, where am I going wrong?
WITH OwnerHierarchy AS (
SELECT PairID,
ChildID,
ParentID,
0 AS level
FROM BusinessHierarchy
UNION ALL
SELECT e.PairID,
e.ChildID,
e.ParentID,
level + 1 AS level
FROM BusinessHierarchy AS e
JOIN BusinessHierarchy AS eh ON e.ParentID = eh.ParentID)
SELECT PairID,
ChildID,
ParentID,
level
FROM OwnerHierarchy AS OwnerHierarchy_1
ORDER BY level, ChildID, ParentID
This is ms sql server 2005.