Inserting Multiple Rows in MSSQL

While trying to find a way to insert multiple rows of data in one query using MSSQL, I found a solution on SQLAuthority.com. Their solution involves making use of the UNION ALL statement to combine multiple value statements. The example they give is:

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

This is a great solution and works perfectly. However, I have found that it is not the easiest to remember – I have to go back to that site any time I want to use this because I just can’t remember the exact syntax. I was discussing this solution with a co-worker and he suggested we try something different:

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES
('First', 1),
('Second', 2),
('Third', 3),
('Fourth', 4),
('Fifth', 5);

Sure enough, it works! Not only is it easier to write, but it’s so much easier to remember. Hopefully others will find this as useful as I did.

Bookmark and Share
If you enjoyed this post, make sure you subscribe to my RSS feed!

Filed under Databases · Tagged with , , ,

Comments

One Response to “Inserting Multiple Rows in MSSQL”
  1. UTAlan says:

    SQL Authority made another post that helped me out. Turns out the solution I gave only works in SQL Server 2008. If you have an older version, you’ll have to use UNION ALL.

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!