101

我正在简化一个复杂的选择语句,所以我想我会使用公用表表达式。

声明一个 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 上。

4

2 回答 2

155

我认为它应该是这样的:

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

基本上,WITH这里只是一个子句,和其他包含列表的子句一样,“,”是适当的分隔符。

于 2009-02-25T00:40:31.820 回答
17

上面的答案是对的:

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

于 2015-03-17T16:27:24.880 回答