Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - 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 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?

like image 208
Macs Dickinson Avatar asked Mar 22 '13 15:03

Macs Dickinson


People also ask

Can we use where clause with insert statement in SQL Server?

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.

Can we use with clause in SQL Server?

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.

Can we use with clause in select statement?

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.

What does the with function do in SQL?

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.


1 Answers

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

like image 69
Taryn Avatar answered Sep 30 '22 08:09

Taryn