Wednesday, November 25, 2009

SQL: how to do batch insert

How can I insert multiple values in table using only one insert? Now this is interesting question. When there are multiple records are to be inserted in the table following is the common way using T-SQL.
USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('First',1);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Second',2);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Third',3);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Fourth',4);
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('Fifth',5);
GO


The clause INSERT INTO is repeated multiple times. Many times DBA copy and paste it to save time. There is another alternative to this, using UNION ALL and INSERT INTO … SELECT… clauses.

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO


Performance: some guys did some experiments to verify how about the performance between these two clauses

execute 400 insert statements to table about 20 columns (int or float). Regarding performance there is MUCH difference. ;)

INSERT statements way: about 5 seconds
INSERT SELECT UNION ALL way: 40 miliseconds!!!


so I think if you want to insert a lot of data for one time, the performance has big difference.
but if you just insert 10, 20 statements for one times. there is no performance difference between these two clauses

No comments:

Post a Comment