简体   繁体   中英

Combining two CTEs with UNION causes an error

Getting the following error:

'Msg 156, Level 15, State 1, Line 53
Incorrect syntax near the keyword 'WITH'.

Msg 319, Level 15, State 1, Line 53
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.'

When running the CTE's separately it's fine. But when combining using a UNION.. then the error appears.

With cte1 as 
(
    select
       .
       .
       .

    Select

    from

)
select

UNION

With cte2 as 
(
    Select

    From
)
Select 

from

In SQL Server, CTEs are attached to the outermost select . In other words, there is only one per query and all the definitions must come before the select .

So combine them into a single with :

with cte1 as (
      select . . . 
     ),
     cte2 as (
      select . . .
     )
select . . .
from cte1 . . . 
union
select  . . 
from cte2 . . .;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM