我怎样才能在一个SELECT语句中有多个公用表expression式?
我正在简化一个复杂的select语句的过程中,所以认为我会使用公用表expression式。
声明一个单一的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 ';'.
可能不相关,但这是在SQL 2008。
我认为这应该是这样的:
WITH cte1 as (SELECT * from cdr.Location), cte2 as (SELECT * from cdr.Location) select * from cte1 union select * from cte2
基本上, WITH
就是这里的一个子句,就像其他的子句一样,“,”是合适的分隔符。
上面提到的答案是正确的:
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
只是expression式的假设
希望这个博客也将帮助: http : //iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html