2009-02-25 37 views
80

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

回答

115

我想应该是这样的:

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

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

+0

太棒了。我一直在用CTE的结果填充临时表格并在稍后结合使用,但是在打包到存储过程中遇到了半冒号问题。好方法! – 2011-07-28 16:21:42

+15

不要忘记,`cte2`可以像这样引用`cte1`:... cte2 as(SELECT * FROM cte1 WHERE ...) – Chahk 2013-10-30 13:56:54

10

上面提到的答案是正确的:

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

的方法,另外,您也可以从CTE1查询在CTE2:

WITH 
    cte1 as (SELECT * from cdr.Location), 
    cte2 as (SELECT * from cte1 where val1 = val2) 

select * from cte1 union select * from cte2 

val1,val2是表达式只是asumptions ..

希望本博客也将有所帮助: http://iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html

相关问题