Skip to main content

MERGE in SQL SERVER -INSERT, UPDATE, DELETE in single execution.

To do multiple DML operations in SQL SERVER we use MERGE, that a strong feature of SQL SERVER, In earlier versions of SQL SERVER we had to write separate statement for INSERT, UPDATE, DELETE, now by using MERGE we can perform INSERT, UPDATE, DELETE in one statement by checking data, if data matched then update otherwise insert or in particular condition we can also delete.
Note-Merge statement read entire data and processed only one.
The Merge query is given below:
Suppose there are two tables, Table1 and table2, table1 contains data about books like ISBN, Title, quantity, price, etc.. and table2 contains updated data of book so here we need to update Table1 from Table2, Table may have new records or updated records(like quantity, price etc ) or it may be some records should be delete from Table1.
CREATE  TABLE TABLE1
(
biBookId BIGINT IDENTITY(1,1),
vIsbn VARCHAR(20),
iQty INT,
dcPrice DECIMAL(18,2)
)
CREATE  TABLE TABLE2
(
biBookId BIGINT IDENTITY(1,1),
vIsbn VARCHAR(20),
iQty INT,
dcPrice DECIMAL(18,2)
)
/*insert some data in table1*/
INSERT INTO TABLE1(vIsbn,iQty,dcPrice) VALUES('9987876543343',10,0.00)
INSERT INTO TABLE1(vIsbn,iQty,dcPrice) VALUES('8898576476532',1,21.30)
INSERT INTO TABLE1(vIsbn,iQty,dcPrice) VALUES('9898765456763',50,4.00)
INSERT INTO TABLE1(vIsbn,iQty,dcPrice) VALUES('8987655663452',0,5.00)
/*insert some data in table2*/
INSERT INTO TABLE2(vIsbn,iQty,dcPrice) VALUES('9987876543343',20,0.00)
INSERT INTO TABLE2(vIsbn,iQty,dcPrice) VALUES('8898576476532',1,31.30)
INSERT INTO TABLE2(vIsbn,iQty,dcPrice) VALUES('9898765456763',5,4.00)
INSERT INTO TABLE2(vIsbn,iQty,dcPrice) VALUES('8987655663452',0,15.00)
INSERT INTO TABLE2(vIsbn,iQty,dcPrice) VALUES('8987655663451',11,25.00)
/*data in table1 before merge*/
select * from TABLE1
/*MERGE statement*/
MERGE TABLE1 AS tbl1
USING (SELECT  vIsbn,iQty,dcPrice FROM TABLE2) as tbl2
ON tbl1.vIsbn=tbl2.vIsbn
WHEN MATCHED AND tbl2.iQty=0 THEN DELETE
WHEN MATCHED THEN UPDATE
SET tbl1.iQty=tbl2.iQty,
tbl1.dcPrice=tbl2.dcPrice
WHEN NOT MATCHED THEN
INSERT(vIsbn,iQty,dcPrice)
VALUES(tbl2.vIsbn, tbl2.iQty, tbl2.dcPrice);
GO
SELECT * FROM TABLE1
DROP TABLE TABLE1
DROP TABLE TABLE2

Comments

  1. Hi Dilip,
    On duplicate records Merge is failed, any idea to prevent it.

    ReplyDelete

Post a Comment

Popular posts from this blog

Inner join in sql server

INNER JOIN Inner join responsible to returns rows which have a match in both tables. See following example:- CREATE TABLE #ORDER ( orderId INT IDENTITY ( 1 , 1 ), fName VARCHAR ( 400 ), lName VARCHAR ( 400 ), ShipAddress VARCHAR ( 1000 ), dtCreate DATETIME ) CREATE TABLE #ORDER_DETAILS ( orderDetailsId INT IDENTITY ( 1 , 1 ), productName VARCHAR ( 400 ), pPrice DECIMAL ( 18 , 2 ), iQTY INT , orderId INT , dtCreate DATETIME ) INSERT INTO #ORDER ( fName , lName , ShipAddress , dtCreate ) SELECT 'Dilip' , 'SINGH' , 'New Delhi' , GETDATE () UNION ALL SELECT 'Nirmit' , 'katiyar' , 'Mumbai' , GETDATE () UNION ALL SELECT 'Raj' , 'Dongra' , 'Jharkhand' , GETDATE () UNION ALL SELECT 'Salim' , 'safi' , 'Muradnagar UP' , GETDATE () INSERT INTO #ORDER_DETAILS ( productName , pPrice , iQTY , orderId , dtCreate ) SELE

Constraints in sql server

Constraints   - Constraints are the rules enforced on data columns on table. This ensures the accuracy and reliability of the data in the database. Constraints define some conditions that restricts the column to remain true while inserting or updating or deleting data in column. Constraints can be defined in two ways   1) The constraints can be specified immediately after the column definition. This is called column-level definition.   2) The constraints can be specified after all the columns are defined. This is called table-level definition.   Types of Constraints in SQL-Server NOT NULL - This constraint is responsible for a column to confirm that a column cannot have a null value. DEFAULT – This constraint provides a default value when specified non for this column. UNIQUE - This constraint insure that each row for the column has different value. PRIMARY KEY - Primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constra

NOT NULL constraint in sql server

NOT NULL- This constraint is responsible for a column to confirm that a column cannot have a null value. Example- Following we create new table PRODUCT and add six columns where ID, SKU, TITLE, PRICE specify not to accept NULLs. CREATE TABLE PRODUCT ( ID INT NOT NULL, SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL ) If PRODUCT table already created, then to add a NOT NULL constraints to SKU column we use following query.   ALTER TABLE PRODUCT   ALTER COLUMN SKU  VARCHAR ( 20 ) NOT NULL