Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have multiple common table expressions in a single SELECT statement?

I am in the process of simplifying a complicated select statement, so thought I would use common table expressions.

Declaring a single cte works fine.

WITH cte1 AS (     SELECT * from cdr.Location     )  select * from cte1  

Is it possible to declare and use more than one cte in the same SELECT?

ie this sql gives an error

WITH cte1 as (     SELECT * from cdr.Location )  WITH cte2 as (     SELECT * from cdr.Location )  select * from cte1     union      select * from cte2 

the error is

Msg 156, Level 15, State 1, Line 7 Incorrect syntax near the keyword 'WITH'. Msg 319, Level 15, State 1, Line 7 Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. 

NB. I have tried putting semicolons in and get this error

Msg 102, Level 15, State 1, Line 5 Incorrect syntax near ';'. Msg 102, Level 15, State 1, Line 9 Incorrect syntax near ';'. 

Probably not relevant but this is on SQL 2008.

like image 625
Paul Rowland Avatar asked Feb 25 '09 00:02

Paul Rowland


People also ask

Can we use two CTE in a single SELECT query?

After learning common table expressions or CTEs, a natural question is “Can I use several CTEs in one query?” Yes, you can!

How do I create multiple CTE?

The same steps for adding a second CTE can be repeated to add a third, fourth, or more CTE queries. The steps to add a second CTE into a query are: Add a comma at the end of the first CTE, after the closing parentheses. After the comma, on the next line, declare the name of the new CTE.

Can I use CTE multiple times?

Unlike a derived table, a CTE behaves more like an in-line view and can be referenced multiple times in the same query. Using a CTE makes complex queries easier to read and maintain. Because a CTE can be referred to multiple times in a query, syntax can be simpler.


1 Answers

I think it should be something like:

WITH      cte1 as (SELECT * from cdr.Location),     cte2 as (SELECT * from cdr.Location) select * from cte1 union select * from cte2 

Basically, WITH is just a clause here, and like the other clauses that take lists, "," is the appropriate delimiter.

like image 96
MarkusQ Avatar answered Oct 16 '22 09:10

MarkusQ