当前位置:  开发笔记 > 数据库 > 正文

如何在单个SELECT语句中使用多个公用表表达式?

如何解决《如何在单个SELECT语句中使用多个公用表表达式?》经验,为你挑选了2个好方法。

我正在简化复杂的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 ';'.

可能不相关,但这是在SQL 2008上.



1> MarkusQ..:

我认为应该是这样的:

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

基本上,WITH这里只是一个子句,就像采用列表的其他子句一样,","是适当的分隔符.


不要忘记`cte2`可以像这样引用`cte1`:... cte2 as(SELECT*FROM cte1 WHERE ...)

2> Sagar Dev Ti..:

上面提到的答案是对的:

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 只是表达式的假设..

希望这篇博客也能提供帮助:http: //iamfixed.blogspot.de/2017/11/common-table-expression-in-sql-with.html

推荐阅读
拾味湖
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有