views:

36

answers:

5

how can i insert multiple records using single sql statement

A: 

Using MySQL:

INSERT INTO TABLE (col1, col2) VALUES
  (val1a, val1b),
  (val2a, val2b),
  (valNa, valNb);
Lekensteyn
A: 

You should use table types and use bulk insert.

EDIT: http://msdn.microsoft.com/en-us/library/bb510489.aspx

This can explain further on using either one. This works for SQL server, I am not so sure about other databases. Both are very useful for a lot of records to be inserted at one go.

Roopesh Shenoy
how can i do this please let me know
NoviceToDotNet
Just edited my original post - should give you some reference. Both are two different methods and the comparison in the link will help understand which is better in a scenario.
Roopesh Shenoy
+3  A: 

For SQL Server 2005 you could do the following:

INSERT INTO your_table (id, field_1, field_2)
   SELECT 1, 'some-data-a', 'some-data-1'
   UNION ALL
   SELECT 2, 'some-data-b', 'some-data-2'
   UNION ALL
   SELECT 3, 'some-data-c', 'some-data-3'
   UNION ALL
   SELECT 4, 'some-data-d', 'some-data-4';

In most modern DBMSes, including SQL Server 2008 and MySQL 5, you could use a much neater syntax:

INSERT INTO your_table (id, field_1, field_2) VALUES
   (1, 'some-data-a', 'some-data-1'),
   (2, 'some-data-b', 'some-data-2'),
   (3, 'some-data-c', 'some-data-3'),
   (4, 'some-data-d', 'some-data-4');
Daniel Vassallo
i suppose this is supported for sql server 2008 on wordsi am using sql server 2005
NoviceToDotNet
@NoviceToDotNet: For SQL Server 2005, you'll have to use the first option. Also check out: http://stackoverflow.com/questions/2624713/in-tsql-sql-server-how-do-i-insert-multiple-rows-without-repeating-the-insert
Daniel Vassallo
A: 

You can insert multiple records from a subquery as well.

INSERT INTO TABLE (col1, col2) (select a,b from SUB)
Zafer