dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: SQL
Expertise: Intermediate
Aug 16, 2016

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Doing Upserts with the Help of MERGE

There will be times that you encounter a situation where you have to update a row, if it exists, or create a new row if the certain data is not already present. There will also be times when you do not want to Insert any duplicate information into a table. All of these scenarios can be implemented with a well-structured SQL MERGE statement, such as the following:

MERGE [Table] WITH (HOLDLOCK) AS t
USING (VALUES ( @ID)) AS s (ID)
ON s.ID = t.ID
WHEN NOT MATCHED BY TARGET THEN
INSERT (
[Field1],
[Field2],
[Field3]
)

VALUES (
@ValueForField1,
@valueForField2,
@ValueForField3
); 

I checked whether or not an ID already exists inside the table named TABLE. If it doesn't exist, it will INSERT a new row, otherwise it won't do anything.

Hannes du Preez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date