Select and Insert in 1 SQL Query

April 12th, 2010
INSERT INTO Table2 (col1, col2)
SELECT col3, col4
FROM Table1

How about a bit detailed example using the following sample database structure.

Table1
===========
Tbl1_ID (going to assume an auto increment here)
FK_Tbl2_ID
Data_Copy

Table2
===========
Tbl2_ID
Data

Query1: Select Tbl2_ID From Table2 Where Data = 1

For every returned record from query1 it should insert a record into Table1

INSERT INTO Table1 (FK_Tbl2_ID, Data_Copy)
SELECT Tbl2_ID, Data
FROM Table2
WHERE Data = 1

If anyone has seen/done any kind of performance testing on this sort of query would you kindly post them below.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>