Translate

Saturday, 21 July 2018

sql merged OR merge statement , use while bulk data is updated

Instead of using cursor use Merged statement for better performance.

Here is an sample code

 CREATE DATABASE PABITRA_MERGE_DB;

 USE PABITRA_MERGE_DB;

CREATE TABLE dbo.TargetTableToUpdate  -- target
(
 Id INT PRIMARY KEY,
 TName VARCHAR(20),
 City varchar(50),
 TotalCount INT
);
CREATE TABLE dbo.SourceTableTobeMatched  -- source
(
 Id INT,
 SName VARCHAR(20),
 City varchar(50)

);

INSERT TargetTableToUpdate VALUES
  (1, 'PABITRA','USA', 0),
  (2, 'ARYA', 'BHUBANESWAR', 0),
  (3, 'BRAJA','BANGALORE', 0),
  (5, 'MICROSOFT','MICROSOFT COP', 0),
  (6, 'GOOGLE','GOOGLE COP', 0),
  (8, 'YAHOO','YAHOO COP', 0);

INSERT SourceTableTobeMatched VALUES
  (1, 'PABITRA','USA'),
  (2, 'PABITRA', 'BHUBANESWAR'),
  (3, 'PABITRA','BANGALORE'),
  (4, 'ARYA','MICROSOFT COP'),
  (5, 'ARYA','GOOGLE COP'),
  (6, 'BRAJA','YAHOO COP')



  MERGE TargetTableToUpdate T
USING SourceTableTobeMatched S
ON T.ID = S.ID
WHEN MATCHED THEN
  UPDATE
  SET T.TotalCount =T.TotalCount+1;

  SELECT * FROM TargetTableToUpdate;
  SELECT * FROM SourceTableTobeMatched;

No comments:

Post a Comment