MERGE STATEMENT IN SQL SERVER


DECLARE @TEST TABLE(DATA VARCHAR(20),ID INT)
INSERT INTO @TEST VALUES('RAJU',1)
INSERT INTO @TEST VALUES('RANI',2)
INSERT INTO @TEST VALUES('MANU',3)

DECLARE @MERGTEST TABLE(DATA VARCHAR(20),ID INT)
INSERT INTO @MERGTEST VALUES('RAJU',1)
INSERT INTO @MERGTEST VALUES('RANI',2)
INSERT INTO @MERGTEST VALUES('JONSON',4)

SELECT 'NON MERGED TABLE TEST',* FROM @TEST
SELECT 'NON MERGED TABLE MERGTEST',* FROM @MERGTEST

MERGE INTO @TEST AS TEST
USING(SELECT DATA,ID FROM @MERGTEST) AS MERGTEST(DATA,ID)
ON TEST.DATA=MERGTEST.DATA AND TEST.ID=MERGTEST.ID
WHEN NOT MATCHED BY TARGET THEN
INSERT(DATA,ID) VALUES(MERGTEST.DATA,MERGTEST.ID);

SELECT 'MERGED TABLE TEST',* FROM @TEST

No comments:

Post a comment