Why cannot we use outer joins in Recursive CTE?

Another option would be to define a foundational CTE with de LEFT OUTER JOINS, and then use it as a table in your recursive CTE:

WITH 
InitialQuery as (
    -- here de left outer joins


),

GetParentOfChild AS
(
        FROM InitialQuery 
)

SELECT TOP 1 @ChildId = Parents 
FROM GetParentOfChild
ORDER BY Rn DESC

Yes, it is by design, read Guidelines for Defining and Using Recursive Common Table Expressions

The following items are not allowed in the CTE_query_definition of a recursive member:

  • SELECT DISTINCT
  • GROUP BY
  • HAVING
  • Scalar aggregation
  • TOP
  • LEFT, RIGHT, OUTER JOIN (INNER JOIN is allowed)
  • Subqueries

Notice that if your query make a left join to it self through CTE can become to an infinite recursion.


You can't use LEFT JOIN with recursive CTE but you can use OUTER APPLY which should give the same results.

So...

LEFT OUTER JOIN table tb2 on tb1.Prop = tb2.Prop

becomes...

OUTER APPLY (select * from table tb2 where tb1.Prop = tb2.Prop) tb2