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

标签 sql sql-server sql-server-2008 tsql common-table-expression

我正在简化复杂的 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 上。

最佳答案

我认为应该是这样的:

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

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

关于sql - 如何在单个 SELECT 语句中拥有多个公用表表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/584284/

相关文章:

sql - T-SQL 中的 CALL 和 EXEC 有什么区别?

sql - 如何在存储过程中将表声明为参数

sql - 基于两个表的select CASE语句

sql - 查找在逗号分隔值内包含相同值的行

c# - 从 SQL Server 中的 SELECT 获取 bool 值到 C# 中的 bool 值?

sql-server - SQL Server 2008 中的 bigint 算术溢出

mysql - 加入、分组、排序

android - 如何在单个命令中使用 sqlite 截断数据库(清除数据库中所有表的记录)

sql - 查找所有列的空/空记录数

sql-server - SAN 上的数据共享卷(多个 MDF)和另一个日志共享卷(多个 LDF)