Click here to Skip to main content
15,915,048 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends.

I have following MERGE query. I have two table in same database.

1. INVENTORY as destination table and 2. INVENTORY_STAGE as source table.
SQL
MERGE INVENTORY AS D
USING INVENTORY_STAGE AS S
ON (D.CODE = S.CODE)
WHEN NOT MATCHED
    THEN INSERT(CODE,INV_DESCRIPTION,BVRVMODDATE) VALUES(S.CODE,S.INV_DESCRIPTION,S.BVRVMODDATE)
WHEN MATCHED AND (S.BVRVMODDATE <> D.BVRVMODDATE)
    THEN UPDATE
    SET CODE=S.CODE,INV_DESCRIPTION=S.INV_DESCRIPTION,BVRVMODDATE=S.BVRVMODDATE;


The above query check if data is matched with CODE value then it is updated in destination otherwise it is inserted to destination.

My requirement is that is data is not exist in source table and exist in destination table then record should be deleted from destination table,

Where it would be change in above query?
Regard

Imrankhan
Posted
Updated 9-Jan-17 21:49pm

Reading though MERGE (Transact-SQL)[^] it seems you have to use WHEN NOT MATCHED BY SOURCE THEN.
 
Share this answer
 
I am getting following error.

An action of type 'DELETE' is not allowed in the 'WHEN NOT MATCHED' clause of a
MERGE statement.

my query is like below.
SQL
MERGE CUS2 AS TARGET
USING CUS1 AS SOURCE
ON (TARGET.CUSNUMBER = SOURCE.CUSNUMBER)
WHEN MATCHED 
    THEN UPDATE
    SET 
    CUSNUMBER = SOURCE.CUSNUMBER
WHEN NOT MATCHED BY TARGET THEN
    DELETE
WHEN NOT MATCHED 
    THEN INSERT(CUSNUMBER) VALUES(SOURCE.CUSNUMBER);
 
Share this answer
 
Comments
André Kraak 29-Sep-11 8:53am    
Please to do not post additions to your question as a solution. If you wish to change your question use the Improve Question button.
Using an solution like this will give the people the impression that your question has been answered and perhaps not look at it, causing you not to get an answer to your question.

Please move the content of this solution to your question and remove the solution. Thank you.
André Kraak 29-Sep-11 9:00am    
Replace "BY TARGET" with "BY SOURCE".
MERGE INVENTORY AS D
USING INVENTORY_STAGE AS S
ON (D.CODE = S.CODE)
WHEN NOT MATCHED BY TARGET
THEN INSERT(CODE,INV_DESCRIPTION,BVRVMODDATE) VALUES(S.CODE,S.INV_DESCRIPTION,S.BVRVMODDATE)
WHEN MATCHED AND (S.BVRVMODDATE <> D.BVRVMODDATE)
THEN UPDATE
SET CODE=S.CODE,INV_DESCRIPTION=S.INV_DESCRIPTION,BVRVMODDATE=S.BVRVMODDATE
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900