Merge Statement to perform insert , update and delete in one statement

This example, demonstrate how to perform insert, update and delete on single statement using MERGE. If you are a Database Developer/BI expert, you would need to refresh the target table to match the source tables periodically. Prior to SQL Server 2008, you would need to perform this task by writing separate T-SQL logic for insert, delete and update. Starting from SQL Server 2008, you can perform all three SQL Statements (Insert, Update and Delete) in one statement using MERGE Statement.

What is the use of MERGE statement in SQL Server?

Merge statement introduced in SQL Server 2008 allows us to perform inserts, updates and deletes in one statement, which means we no longer have to use multiple statements to perform insert, update and delete.

Basic Merge syntax:

Merge_Statement

To try the example , you’ll need to first run the following script to create and populate the tables used in the examples:

 -- CREATE A SOURCE TABLE
CREATE TABLE [DBO].[STUDENT_SOURCE](
[ID] [INT] NOT NULL,
[STUDENTNAME] [NCHAR](50) NOT NULL,
CONSTRAINT [PK_STUDENT_SOURCE] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] 
 -- CREATE A TARGET TABLE</pre>
CREATE TABLE [DBO].[STUDENT_TARGET](
[ID] [INT] NOT NULL,
[STUDENTNAME] [NCHAR](50) NOT NULL,
CONSTRAINT [PK_STUDENT_TARGET] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] 
 --- INSERT RECORDS INTO SOURCE TABLE
INSERT INTO [STUDENT_SOURCE] VALUES (1,'RAMA')
INSERT INTO [STUDENT_SOURCE] VALUES (2,'SANKAR')
--- INSERT RECORDS INTO TARGET TABLE
INSERT INTO [STUDENT_TARGET] VALUES (1, 'RAMASANKAR')
INSERT INTO [STUDENT_TARGET] VALUES (3, 'MURTHY') 

After you ran the above script, you have two tables(STUDENT_SOURCE and STUDENT_TARGET)  created with some sample data as below.

Tables

Now, I will use MERGE statement to synchronize target table with source.

 MERGE [STUDENT_TARGET] AS T
USING [STUDENT_SOURCE] AS S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.STUDENTNAME = S.STUDENTNAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, STUDENTNAME) VALUES (S.ID,S.STUDENTNAME)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
(3 row(s) affected) 

There you go, Three rows are modified which means one update, one Insert  and one Delete performed in single statement.

After executing the Merge statement we can see that both source and target are identical.

 SELECT * FROM STUDENT_SOURCE;</pre>
SELECT * FROM STUDENT_TARGET; 

After_Table

MERGE statement is very useful improvement to update database tables with complex logic. Better Performance and scalability can be achieved with MERGE statement.

Hope you enjoyed the post!

Cheers

Ramasankar Molleti

LinkedIn: LinkedIn Profile

Twitter: Twitter

Published by Ramasankar

Hi. I’m Ramasankar Molleti. I’m a passionate IT professional with over 14 years of experience on providing solutions for customers who are looking on cloud computing, Database Migration, Development, and Big Data. I love learning new technologies and share my knowledge to community. I am currently working as Sr Cloud Architect with focus on Cloud Infrastructure, Big Data. I work with developers to architect, build, and manage cloud infrastructure, and services. I have deeep knowledge and experience on working with various database platforms such as MS SQL Server, PostgeSQL, Oracle, MongoDB, Redshift, Dyanamodb, Amazon Aurora. I worked as Database Engineer, Database Administrator, BI Developer and successfully transit myself into Cloud Architect with focus on Cloud infranstructure and Big Data. I live in USA and put my thoughts down on this blog. If you want to get in touch with me, contact me on my Linkedin here: https://www.linkedin.com/in/ramasankar-molleti-23b13218/ My Certifications: Amazon: AWS Certified Solutions Architect – Professional AWS Certified DevOps Engineer – Professional certificate AWS Certified Big Data – Specialty AWS Certified Security – Specialty certificate AWS Certified Advanced Networking – Specialty certificate AWS Certified Solutions Architect – Associate Microsoft: Microsoft® Certified Solutions Associate: SQL Server 2012/2014 Microsoft Certified Professional Microsoft® Certified IT Professional: Database Administrator 2008 Microsoft® Certified Technology Specialist: SQL Server 2008, Implementation and Maintenance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: