我正在简化一个复杂的select语句,因此我想我会使用公用表表达式。如何在单个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.
NB。我试图把分号和得到这个错误
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ';'.
可能不相关,但是这是在2008年的SQL
太棒了。我一直在用CTE的结果填充临时表格并在稍后结合使用,但是在打包到存储过程中遇到了半冒号问题。好方法! – 2011-07-28 16:21:42
不要忘记,`cte2`可以像这样引用`cte1`:... cte2 as(SELECT * FROM cte1 WHERE ...) – Chahk 2013-10-30 13:56:54