Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

I know I've done this before years ago, but I can't remember the syntax, and I can't find it anywhere due to pulling up tons of help docs and articles about "bulk imports".

Here's what I want to do, but the syntax is not exactly right... please, someone who has done this before, help me out :)

INSERT INTO dbo.MyTable (ID, Name) VALUES (123, 'Timmy'),     (124, 'Jonny'),     (125, 'Sally') 

I know that this is close to the right syntax. I might need the word "BULK" in there, or something, I can't remember. Any idea?

I need this for a SQL Server 2005 database. I've tried this code, to no avail:

DECLARE @blah TABLE (     ID INT NOT NULL PRIMARY KEY,     Name VARCHAR(100) NOT NULL )  INSERT INTO @blah (ID, Name)     VALUES (123, 'Timmy')     VALUES (124, 'Jonny')     VALUES (125, 'Sally')  SELECT * FROM @blah 

I'm getting Incorrect syntax near the keyword 'VALUES'.

like image 214
Timothy Khouri Avatar asked Apr 12 '10 19:04

Timothy Khouri


People also ask

How can insert multi rows in only one insert statement?

Answer. Yes, instead of inserting each row in a separate INSERT statement, you can actually insert multiple rows in a single statement. To do this, you can list the values for each row separated by commas, following the VALUES clause of the statement.

How do I insert the same data in multiple rows?

MySQL INSERT multiple rows statement In this syntax: First, specify the name of table that you want to insert after the INSERT INTO keywords. Second, specify a comma-separated column list inside parentheses after the table name. Third, specify a comma-separated list of row data in the VALUES clause.

Which query is used to insert multiple rows into a table?

The INSERT statement also allows you to insert multiple rows into a table using a single statement as the following: INSERT INTO table_name(column1,column2…) VALUES (value1,value2,…), (value1,value2,…), … In this form, you need to provide multiple lists of values, each list is separated by a comma.


1 Answers

Your syntax almost works in SQL Server 2008 (but not in SQL Server 20051):

CREATE TABLE MyTable (id int, name char(10));  INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');  SELECT * FROM MyTable;  id |  name ---+--------- 1  |  Bob        2  |  Peter      3  |  Joe        

1 When the question was answered, it was not made evident that the question was referring to SQL Server 2005. I am leaving this answer here, since I believe it is still relevant.

like image 144
Daniel Vassallo Avatar answered Oct 14 '22 06:10

Daniel Vassallo