简体   繁体   English

多个SQL WITH子句-为什么不呢?

[英]Multiple SQL WITH clauses - why not?

I had 2 separate queries. 我有2个独立的查询。

Query 1: 查询1:

With A as (Select P,Q,R from X union all Select P,Q,R from Y)
Insert into File1
Select * from A

Query 2: 查询2:

With B as (Select S,T,U from Z)
Insert into File2
Select * from B

I realised that,logically, I always need to produce File1 and File2 together, so I decided to just merge the 2 queries into one Stored Procedure. 我意识到,从逻辑上讲,我始终需要同时生成File1和File2,因此我决定将这两个查询合并到一个存储过程中。 However, when I tried to do it, I hit this problem where it's only possible to have one WITH clause in a query. 但是,当我尝试这样做时,我遇到了这个问题,即在查询中只能有一个WITH子句。

So, I found a few questions in SO where people explained that you just use a comma and have a separate WITH clause (albeit, without the WITH) but this wouldn't work in any form for my example. 因此,我在SO中发现了几个问题,人们在其中解释说,您只是使用逗号并有一个单独的WITH子句(尽管没有WITH),但这在我的示例中无法以任何形式使用。

It wasn't a problem - I've easily worked around it by using temporary tables etc. But I'm really intrigued as to why I can't have two entirely unrelated WITH clauses in the same Proc? 这不是问题-我已经通过使用临时表等轻松地解决了这个问题。但是,我对为什么在同一Proc中不能拥有两个完全不相关的WITH子句感到非常好奇。

Can anyone explain please? 谁能解释一下?

You should be able to have 2 WITH clauses, you just need a semicolon after the first one. 您应该能够有2个WITH子句,只需要在第一个子句后加上分号即可。

With A as (Select P,Q,R from X union all Select P,Q,R from Y)
Insert into File1
Select * from A;


With B as (Select S,T,U from Z)
Insert into File2
Select * from B

This is the error you would get from SQL if you are trying to do two without semicolon: 如果您尝试做两个没有分号的错误,这是您从SQL中获得的错误:

Msg 336, Level 15, State 1, Line 6
Incorrect syntax near 'B'. If this is intended to be a common table expression, you need to explicitly terminate the previous statement with a semi-colon.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM