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 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.
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'.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.
Is what I am trying to do possible with different some different syntax?
5条答案
按热度按时间1tu0hz3e1#
You will need to place the
INSERT INTO
right after theCTE
. So the code will be:See SQL Fiddle with Demo
iqjalb3h2#
Another way without using a
CTE
is by wrapping it in a subquery,snvhrwxg3#
Semicolon is used to terminate the statement. So when you use ;WITH, terminates the previous statement. 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 statement can be used in 2 ways - by providing VALUES explicitly or by providing a result set using SELECT statement.
tpxzln5u4#
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:
Z
mfuanj7w5#
on
db2
is possible.Disclaimer
I will be using a complete different example for the answer purposes.
SQL script
Result set
I hope it helps you!