我正在简化一条复杂的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 的。
cte2
可以像这样引用cte1
:... cte2 as (SELECT * FROM cte1 WHERE ...) - Chahk