Insert Multiple Records Using One Insert Statement

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  (FirstColSecondCol)
        VALUES (‘First’,1);
INSERT INTO MyTable  (FirstColSecondCol)
        VALUES (‘Second’,2);
INSERT INTO MyTable  (FirstColSecondCol)
        VALUES (‘Third’,3);
INSERT INTO MyTable  (FirstColSecondCol)
        VALUES (‘Fourth’,4);
INSERT INTO MyTable  (FirstColSecondCol)
        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, which I use frequently. I use UNION ALL and INSERT INTO … SELECT… clauses. Regarding performance there is not much difference. If there is performance difference it does not matter as I use this for one time insert script. I enjoy writing this way, as it keeps me focus on task, instead of copy paste. I have explained following script to new developer. He was quite pleased.

USE YourDB
GO
INSERT INTO MyTable  (FirstColSecondCol)
    SELECT  ‘First’ ,1
    UNION ALL
SELECT  ‘Second’ ,2
    UNION ALL
SELECT  ‘Third’ ,3
    UNION ALL
SELECT  ‘Fourth’ ,4
    UNION ALL
SELECT  ‘Fifth’ ,5
GO

The effective result is same.

Ref :- http://blog.sqlauthority.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: