.
Update: For SQL Server 2008 there is even better method of Row Construction, please read it here : SQL SERVER - 2008 - Insert Multiple Records Using One Insert Statement - Use of Row Constructor
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, 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 (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
Solution for the QlikView, Biztalk, DotNet and MSBI real time development problems
Search This Blog
Monday, November 24, 2008
Subscribe to:
Comments (Atom)
Popular Posts
-
For MVC Interview Questions Part 1 refer below link: http://challadotnetfaq.blogspot.co.uk/2013/12/mvc-interview-questions-and-answers.ht...
-
MVC: Handling Multiple button submission from one view While developing any web applications we use to design lot more forms. Most of...
-
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your compon...
-
Object Dynamic Var Can able to store any kind of value, because object is the base class of all type in .net framework. Can able to s...
-
//insert data into excel sheet private void btnSave_Click(object sender, EventArgs e) { using (OleDbConnection excelConnection = new O...