简体   繁体   English

在 INSERT 语句中使用 WITH 子句

[英]Using the WITH clause in an INSERT statement

I was wondering if this was possible.我想知道这是否可能。 I have an existing query that uses the WITH clause to apply some aggregated data to a SELECT query like so: (massively simplified)我有一个现有查询,它使用WITH子句将一些聚合数据应用于SELECT查询,如下所示:(大量简化)

;WITH alias (y,z)
AS
(
    SELECT y,z FROM tableb
)
SELECT y, z FROM alias

I now want to INSERT the results of this query into another table.我现在想将此查询的结果INSERT到另一个表中。

I have tried the following:我尝试了以下方法:

INSERT INTO tablea(a,b)
;WITH alias (y,z)
AS
(
    SELECT y,z FROM tableb
)
SELECT y, z FROM alias

but I get the error:但我得到了错误:

Incorrect syntax near ';'. ';' 附近的语法不正确。

So I have tried without the semicolon but got the error:因此,我尝试不使用分号,但出现错误:

Incorrect syntax near the keyword 'WITH'.关键字“WITH”附近的语法不正确。

Incorrect syntax near the keyword 'with'.关键字“with”附近的语法不正确。 If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.如果此语句是公用表表达式或 xmlnamespaces 子句,则前面的语句必须以分号结束。

Is what I am trying to do possible with different some different syntax?我正在尝试用不同的一些不同的语法来做可能的事情吗?

You will need to place the INSERT INTO right after the CTE . 您需要在CTE之后立即放置INSERT INTO So the code will be: 所以代码将是:

;WITH alias (y,z)
AS
(
    SELECT y,z FROM tableb
)
INSERT INTO tablea(a,b)
SELECT y, z 
FROM alias

See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo

Another way without using a CTE is by wrapping it in a subquery, 不使用CTE另一种方法是将其包装在子查询中,

INSERT INTO tablea(a,b)
SELECT y, z 
FROM 
(
    SELECT y,z FROM tableb
) alias

Semicolon is used to terminate the statement. 分号用于终止语句。 So when you use ;WITH, terminates the previous statement. 因此,当您使用; WITH时,终止前一个语句。 However, that's not why you are getting the error here. 但是,这不是你在这里得到错误的原因。 The problem here is with your INSERT INTO statement, which is looking for VALUES or SELECT syntax. 这里的问题是你的INSERT INTO语句,它正在寻找VALUES或SELECT语法。

INSERT INTO statement can be used in 2 ways - by providing VALUES explicitly or by providing a result set using SELECT statement. INSERT INTO语句可以通过两种方式使用 - 通过显式提供VALUES或使用SELECT语句提供结果集。

In my case the suggested answer was unappliable, I could think it is a metter of SQL Server Version which in my case is SQL Server 2016. Alternatively you could use temp tables through this snippet of code:在我的情况下,建议的答案不适用,我认为这是 SQL 服务器版本的米,在我的情况下是 SQL Server 2016。或者,您可以通过以下代码片段使用临时表:

;WITH alias (y,z)
AS (SELECT y,z FROM tableb)
SELECT Y,Z
INTO #TEMP_TABLE
FROM alias

Z Z

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

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