Friday, October 1, 2010

Recursive common table expression 'TableName' does not contain a top-level UNION ALL operator.

I've started using CTEs (Common Table Expressions) a lot. I find they can make my code quite a bit easier to read. But just now, working on a SQL statement with a CTE, it took me a while to figure out why I was getting this error message:

Msg 252 
Recursive common table expression [TableName] does not contain a top-level UNION ALL operator.


It was a long and complex sql statement with multiple CTEs, which obscured the real problem. The little I found online wasn't helping either. I ended up going step by step, and stripping out everything from the SQL statement. Finally I ended up with something similar to this, which returns the error:

;With table1 AS
(
Select field1 from table1 where field1 = 1
)
Select * from table1



At this point it was obvious—you can't name your CTE with the same name as a table it's referencing. So the answer was to rename my CTE to something like this:

;With table1_filtered AS
(
Select field1 from table1 where field1 = 1
)
Select * from table1



There's other conditions that can cause this error to occur as well, but I didn't see this one described online anywhere. If you have this problem as well, feel free to comment.

3 comments:

  1. Thanks, this really helped me out.

    ReplyDelete
  2. Thank you very much. this solved a problem i have been banging my head for atleast 4 hours

    ReplyDelete
  3. This helped me out too, I had the same issue.

    ReplyDelete