.
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
SQL SERVER - Insert Multiple Records Using One Insert Statement - Use of UNION ALL
Labels:
Sql Server
Subscribe to:
Post Comments (Atom)
Popular Posts
-
Qlikview developer, Designer and admin interview questions (Qlikview developer, Designer and admin FAQ’S) 1. Difference between Set ...
-
.Net Integration with Bill Desk Payment Gateway Introduction: Now-a-days online shopping websites has become very popular, and to h...
-
What is "Big Data"? The short answer is that size does matter after all. Sometimes big data is measured in terabytes, petabytes...
-
BizTalk Developer Interview Questions and Answers : Schema 1. What is the purpose of a document schema? The schema is basically a contr...
-
Major difference between WCF SOAP and WCF REST is flexibility. WCF SOAP services supports a wide range of transport protocols, including...
No comments:
Post a Comment