Lets say you have a table as such (SQL SERVER 2005)
pairID childID parentID
0 1 2
1 2 3
2 3 4
And you have a CTE that return this dataset:
pairID childID parentID level
0 1 2 2
1 2 3 1
2 3 4 0
How do you save the initial child ID so that you would get this result set instead:
pairID childID parentID level
0 1 2 2
1 1 3 1
2 1 4 0
So basically what I am doing is keeping the original child id and returning that instead of the other...
This is the CTE query to date, which works perfectly:
WITH TESTER AS (SELECT a.PairID,
a.ChildID,
a.ParentID,
0 AS Level
FROM
BusinessHierarchy AS a
LEFT OUTER JOIN BusinessHierarchy AS a2
ON a.ParentID = a2.ChildID
WHERE (a2.PairID IS NULL)
UNION ALL
SELECT b.PairID, b.ChildID, b.ParentID, oh.Level + 1 AS Level
FROM BusinessHierarchy AS b INNER JOIN
TESTER AS oh ON b.ParentID = oh.ChildID)
SELECT PairID, ChildID, ParentID, Level
FROM TESTER AS x
ORDER BY Level, ChildID, ParentID