SQL SERVER – Insert Multiple Records Using One Insert Statement

Earlier I was struggling a lot by writing multiple statements for each Insert to the single table. Infact in Respond, we have to write individual classes for each statement. At last I got a solution to manage with a single statement.
Absolutely helpful to me that I will be able to insert multiple rows in SQL with using only one SELECT statement.

Previous method 1:
USE MyDB
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

Previous method 2:
USE MyDB
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

SQL Server 2008 Method of Row Construction:
USE MyDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

Thanks a lot to my friend who let me know about it :-)

Keep coding... !

Comments

Popular posts from this blog

Interview Questions to Ask the Employer

Place .NET DLL in GAC

Windows Communication Foundation - FAQ