I'm running into an issue with a recursive CTE giving me odd results when combined with an outer join.Here's a test case to demonstrate what I'm talking about:DECLARE @Items table ( ItemID int, ParentID int null);DECLARE @SideTable table ( SideTableID int, ItemID int);INSERT INTO @Items VALUES (1,NULL);INSERT INTO @Items VALUES (2,NULL);INSERT INTO @Items VALUES (3,NULL);INSERT INTO @Items VALUES (4,1);INSERT INTO @Items VALUES (5,1);INSERT INTO @Items VALUES (6,4);INSERT INTO @Items VALUES (7,6);INSERT INTO @Items VALUES (8,6);INSERT INTO @SideTable VALUES (100,1);INSERT INTO @SideTable VALUES (101,6);INSERT INTO @SideTable VALUES (102,8);WITH CTE_Items (ItemID, ParentItemID, SideTableID, HierarchyLevel) AS( SELECT A.ItemID, A.ParentID, B.SideTableID, 1 AS HierarchyLevel FROM @Items AS A LEFT JOIN @SideTable AS B ON A.ItemID = B.ItemID WHERE A.ParentID IS NULL UNION ALL SELECT A.ItemID, A.ParentID, CTE.SideTableID, (CTE.HierarchyLevel + 1) AS HierarchyLevel FROM @Items AS A INNER JOIN CTE_Items AS CTE ON A.ParentID = CTE.ItemID)SELECT * FROM CTE_Items;
This is the result set:ItemID ParentItemID SideTableID HierarchyLevel1 NULL 100 12 NULL NULL 13 NULL NULL 14 1 100 25 1 100 26 4 100 37 6 100 48 6 100 4
Notice how all of the children of ItemID 1 are showing the SideTableID of ItemID 1? That's not right.The DESIRED result set is this:ItemID ParentItemID SideTableID HierarchyLevel1 NULL 100 12 NULL NULL 13 NULL NULL 14 1 NULL 25 1 NULL 26 4 101 37 6 NULL 48 6 102 4
I tried modifying the recursive part of the CTE to this: SELECT A.ItemID, A.ParentID, B.SideTableID, (CTE.HierarchyLevel + 1) AS HierarchyLevel FROM @Items AS A LEFT JOIN @SideTable AS B ON A.ItemID = B.ItemID INNER JOIN CTE_Items AS CTE ON A.ParentID = CTE.ItemID
But this generates an error:Msg 462, Level 16, State 1, Line 24Outer join is not allowed in the recursive part of a recursive common table expression 'CTE_Items'.Is there something I'm missing? In the past I'd do this by pulling in the entire result set in code and using some recursive functions to build my hierarchy.This is really the first time I'm messing with CTE so it's quite possible I'm missing something simple, or this task is simply not possible with CTE.Help?