Sunday, May 15, 2011

How to write multiple INSERT INTO statements in a single statement

This is a very simple trick but can save you some valubale time. As DBA's and Database Developers we write lot of INSERT INTO statements in our day to day life. So when we want to insert multiple rows we tend to copy and paste the same statement and change the values. An example would be somthing like this;

INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES (1, 'Kaminda', 2000, GETDATE());
INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES (2, 'Hemali', 8500, GETDATE());
INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES (3, 'Jude', 3450, GETDATE());
INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES (4, 'Charith', 4500, GETDATE());
INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES (5, 'Lolitha', 2300, GETDATE());

So to do this in a single statement there are two different ways, first one is for SQL Server 2005 and the second method which is much more easier is only supported by SQL Server 2008 upwards;

In SQL SERVER 2005, you can use UNION ALL to accomplish this;

INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified)
SELECT 1, 'Kaminda', 2000, GETDATE()
UNION ALL
SELECT
2, 'Hemali', 8500, GETDATE()
UNION ALL
SELECT
3, 'Jude', 3450, GETDATE()
UNION ALL
SELECT
4, 'Charith', 4500, GETDATE()
UNION ALL
SELECT 5, 'Lolitha', 2300, GETDATE();


This is supported only SQL Server 2008 onwards;

INSERT INTO tblCustomer (ID,Customer_Name, Credit_Limit, Date_Modified) VALUES
(1, 'Kaminda', 2000, GETDATE()),
(2, 'Hemali', 8500, GETDATE()),
(3, 'Jude', 3450, GETDATE()),
(4, 'Charith', 4500, GETDATE()),
(5, 'Lolitha', 2300, GETDATE());

No comments:

Post a Comment