Insert multiple values sets into a table in one command
8February 28, 2013 by Kenneth Fisher
The INSERT command has two distinct ways to load data into a table.
INSERT INTO Table (field1, field2) VALUES ('string1','string2')
And
INSERT INTO Table (field1, field2) SELECT field1, field2 FROM Table2
Both of these are very handy and have been around as far back as I can remember. Historically you would use the INSERT INTO VALUES to load one row, and the INSERT INTO SELECT to load multiple rows. However as of SQL 2008 the INSERT INTO VALUES was expanded to allow multiple inserts at once.
INSERT INTO Table (field1, field2) VALUES ('string1','string2'), ('stringA','stringB')
This lets you create a single command that will insert multiple rows into a table at once. Basically you list multiple (valuelist)s delimited by commas. There may be a high end to the number of (valuelist)s that you can put in a single command but I haven’t found it yet.
sir i want to insert table2 auto increment id also in table1 how it is possible
If you don’t want to use a second insert command then you need to use a trigger. However either way you can use the scope_identity() function to get the last auto increment id (assuming identity column) created within the current scope.
Kenneth, thank you for your posts that are very helpfull, but regarding inputing several rows in one command, I encountered a problem. I am running EMS light to run the SQL scripts and it is returning a SQL error code -104 (token unknown). This token is the comma at end of the line.
I’ve never used EMS before but I’m going to guess that it wants to treat each line as a separate piece of code. Try removing all carriage returns and see if that fixes it.
Hi Kenneth,
I have a question for you.
I have many SELECT statements in a .txt file. All SELECT’s are on the same table with same metadata. How to execute those quickly in datastage. The output should be Union of all SELECT statement results
I’m afraid I’ve never heard of datastage. My suggestion would be to quickly paste UNION ALL (unless you actually want to get rid of duplicates) between each of your queries then paste the whole thing into a query window.
I don’t need duplicates. But doing UNION of around 1000 SELECT statements is not correct right? what do you say on this. Is it a good option to go for UNIX Script.
You could put UNIONs between each of the statements and I’d bet it would work although you might have to use SQLCMD to run it. It has an option for running a file. Your other option is to create a temp table and do INSERT INTO SELECT on each of them then run a SELECT DISTINCT.
In general though you are probably better off posting this to one of the forums where you can show your whole problem and more people will be looking than just me.