如何在单个SELECT语句中具有多个公用表表达式?


92

我正在简化一个复杂的select语句,因此以为我会使用公用表表达式。

声明单个CTE可以正常工作。

WITH cte1 AS (
    SELECT * from cdr.Location
    )

select * from cte1 

是否可以在同一SELECT中声明和使用多个cte?

即此SQL给出了一个错误

WITH cte1 as (
    SELECT * from cdr.Location
)

WITH cte2 as (
    SELECT * from cdr.Location
)

select * from cte1    
union     
select * from cte2

错误是

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.

注意 我尝试放入分号并出现此错误

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

可能不相关,但这在SQL 2008上。

Answers:


139

我认为应该是这样的:

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

基本上,WITH这里只是一个子句,与其他采用列表的子句一样,“,”是适当的定界符。


棒极了。我一直在用CTE的结果填充临时表并在以后合并,但是在打包到存储的proc中时遇到了半冒号的问题。好方法!
汤姆·哈拉迪

18
别忘了cte2可以cte1像这样引用:... cte2 as(SELECT * FROM cte1 WHERE ...)
Chahk

英雄!这让我感到
难受

2
声明递归和非递归表达式怎么办?
德米特里·沃尔科夫

14

上面提到的答案是正确的:

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

另外,您还可以从cte2中的cte1查询:

WITH 
    cte1 as (SELECT * from cdr.Location),
    cte2 as (SELECT * from cte1 where val1 = val2)

select * from cte1 union select * from cte2

val1,val2 只是表达的假设。

希望该博客对您有所帮助:http : //iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html


声明递归和非递归表达式怎么办?
德米特里·沃尔科夫
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.