Tuesday, October 28, 2008

SQL: INSERT multiple records using one INSERT Statement

What would you do if you want to insert whole table or a whole result from a SELECT statement using only a single line of INSERT statement?

Usually a DB Admin will do this in a copy-paste manner:

INSERT INTO Table1 (Column1, Column2) VALUES ('First' , 1);
INSERT INTO Table1 (Column1, Column2) VALUES ('Second' , 2);

This is the solution:

INSERT INTO Table1 (Column1, Column2) SELECT Column1, Column2 FROM Table2 WHERE Column1 = something;

And to insert complicated results from different tables, use UNION ALL:

INSERT INTO Table1 (Column1, Column2)
SELECT 'First' , 1
UNION ALL
SELECT 'Second' , 2
UNION ALL
SELECT 'Third' , 3
UNION ALL
SELECT 'Fourth' , 4
UNION ALL
SELECT 'Fifth' , 5;

No comments: