如何在单个 SELECT 语句中拥有多个公用表表达式?
Posted
技术标签:
【中文标题】如何在单个 SELECT 语句中拥有多个公用表表达式?【英文标题】:How can I have multiple common table expressions in a single SELECT statement? 【发布时间】:2010-10-09 17:10:56 【问题描述】:我正在简化一个复杂的选择语句,所以我想我会使用公用表表达式。
声明单个 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 上。
【问题讨论】:
【参考方案1】:我认为应该是这样的:
WITH
cte1 as (SELECT * from cdr.Location),
cte2 as (SELECT * from cdr.Location)
select * from cte1 union select * from cte2
基本上,WITH
在这里只是一个子句,和其他包含列表的子句一样,"," 是适当的分隔符。
【讨论】:
太棒了。我一直在用 CTE 的结果填充临时表并稍后组合,但是在打包到存储过程中时遇到了分号问题。不错的方法! 别忘了cte2
可以像这样引用cte1
: ... cte2 as (SELECT * FROM cte1 WHERE ...)
英雄!这让我难倒了好几个小时
声明递归和非递归表达式怎么样?【参考方案2】:
上面的答案是对的:
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
【讨论】:
声明递归和非递归表达式怎么样?以上是关于如何在单个 SELECT 语句中拥有多个公用表表达式?的主要内容,如果未能解决你的问题,请参考以下文章