Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining INSERT INTO and WITH/CTE

I have a very complex CTE and I would like to insert the result into a physical table.

Is the following valid?

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos  (     BatchID,     AccountNo,     APartyNo,     SourceRowID )        WITH tab (   -- some query )     SELECT * FROM tab 

I am thinking of using a function to create this CTE which will allow me to reuse. Any thoughts?

like image 835
dcpartners Avatar asked Jul 22 '10 05:07

dcpartners


People also ask

Can we use insert into in CTE?

You can also use CTE to insert data into the SQL table. The CTE query definition includes the required data that you can fetch from existing tables using joins.

Can we perform DML on CTE?

CTE can be used for both selects and DML (Insert, Update, and Delete) statements.

Can we use CTE in update statement?

CTE is only referenced by select, insert, update and delete statements which immediately follows the CTE expression. In this with clause, you can create multiple CTE tables.

Can we use merge with CTE in SQL?

Merge statement would work perfectly here. Although if we use Data table as the target, we will have hard time to differentiate the customers who didn't submit any data. Fortunately we can put CTE that filters out customers who don't have any orders today and use it as the target.


1 Answers

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (     bla bla ) INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos ( BatchID, AccountNo, APartyNo, SourceRowID )   SELECT * FROM tab 

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

like image 163
Valentino Vranken Avatar answered Sep 27 '22 21:09

Valentino Vranken