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?
Copying specific rows from a table: We can copy specific rows from a table to insert into another table by using WHERE clause with the SELECT statement. We have to provide appropriate condition in the WHERE clause to select specific rows.
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.
The WITH clause allows you, as part of your select statement, to assign a name to a subquery and utilise its results by referencing that name. It is, on first glance, quite jarring. Because the subquery factoring clause brutally transforms the look of a query, making it no longer start with the SELECT keyword.
The WITH clause in SQL was introduced in standard SQL to simplify complex long queries, especially those with JOINs and subqueries. Often interchangeably called CTE or subquery refactoring, a WITH clause defines a temporary data set whose output is available to be referenced in subsequent queries.
You will need to place the INSERT INTO
right after the CTE
. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With