Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple rows into table in SQL Server

I am using to using SQL Server. I'm trying to figure out how to insert multiple rows with one query.

In MySQL the query would be like this:

Code:

INSERT INTO Mytable (Name, Number) VALUES ('Joe', 18), ('Bob', 25), ('Mike', 7);

I tried a query like the one above in SQL Server and it gave me an error that said:

Incorrect syntax near ','.

Is there a way to do this in SQL Server?

like image 954
Pankaj Avatar asked Oct 09 '22 15:10

Pankaj


People also ask

How can I insert multiple rows in a table at a time 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.

How do you insert 3 rows in SQL?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.

How can I insert more than 1000 rows in SQL Server?

Just edit the data in Excel or another program to create N amount of insert statements with a single insert for each statement, you'll have an unlimited number of inserts. For example... This turns out to be a lot faster to achieve than splitting the INSERT statement into batches of 1000 value tuples.


1 Answers

That syntax will work in SQL 2008; in SQL 2005, you have to do SELECTs and UNIONs

INSERT INTO Mytable (Name, Number) 
SELECT 'Joe', 18
UNION ALL SELECT 'Bob', 25
UNION ALL SELECT 'Mike', 7 
like image 124
Stuart Ainsworth Avatar answered Oct 13 '22 11:10

Stuart Ainsworth