Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005: Insert multiple rows with single query

This should be a fairly straightforward question, but I haven't been able to find a solid answer online. I'm trying to insert multiple rows into the same table, but with only one statement. The most popular I've seen online is the following, but I've read that it only works with SQL Server 2008:

INSERT INTO Table (Name, Location) VALUES
('Name1', 'Location1'),
('Name2', 'Location2'),
('Name3', 'Location3'), etc...

I'd prefer this method if it will work with SQL Server 2005, but I don't think it will. The other option, from what I've read, has to do with UNION ALL's following SELECT statements after the INSERT, which seems clunky. Does anyone know for sure the best syntax to do this in 2005?

Thanks.

like image 849
MegaMatt Avatar asked Jul 17 '10 17:07

MegaMatt


People also ask

How do you insert multiple records using a single command in SQL?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

Can we insert multiple rows at a time with single SQL statement?

The number of rows that you can insert at a time is 1,000 rows using this form of the INSERT statement. If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table.

Can insert statement be used to insert multiple rows in a single statement?

Description. The Oracle INSERT ALL statement is used to add multiple rows with a single INSERT statement. The rows can be inserted into one table or multiple tables using only one SQL command.


1 Answers

Yep. You have to use UNION ALLs in SQL Server 2005 to insert multiple rows in a SQL script in a single statement.

INSERT INTO Table 
  (Name, Location) 
SELECT 'Name1', 'Location1' 
UNION ALL
SELECT 'Name2', 'Location2'
UNION ALL
SELECT 'Name3', 'Location3' 

The other main alternative is to repeat the Insert statement multiple times which is even more verbose. You need to be careful to use Explicit transactions in this last case to avoid the overhead of many individual commits (and for atomicity reasons of course)

If you have lots of rows to insert you could use BULK INSERT to load it all in from a delimited file in one statement.

Finally if this is data already in the database that you are scripting out (perhaps to deploy on another server) the SSMS Tools Pack addin has a "Generate Insert Statements" function that can generate these statements for you.

like image 101
Martin Smith Avatar answered Nov 02 '22 23:11

Martin Smith