3

In MERGE statement in SQL Server 2008 exists WHEN NOT MATCHED BY SOURCE and WHEN NOT MATCHED BY TARGET, example taken from Inserting, Updating, and Deleting Data by Using MERGE

-- MERGE statement with join conditions that produce unexpected results.
USE tempdb;
GO
BEGIN TRAN;
MERGE Target AS T
USING Source AS S
ON (T.EmployeeID = S.EmployeeID AND T.EmployeeName LIKE 'S%' 
    AND S.EmployeeName LIKE 'S%' )
WHEN NOT MATCHED BY TARGET
    THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED 
    THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE
    THEN DELETE
OUTPUT $action, Inserted.*, Deleted.*;
ROLLBACK TRAN;
GO

Is there something like this in DB2? For example when I performing MERGE and for any record data in table exists but not in query, NOT MATCH BY SOURCE it will remove data from table.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Anatoly
  • 5,056
  • 9
  • 62
  • 136

1 Answers1

3

I'm currently looking for the answer to the similar question, and as far as I can see, it is not supported by DB2. According the documentation here (http://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.sql.ref.doc/doc/r0010873.html):

NOT MATCHED Indicates the operation to be performed on the rows where the ON search condition is false or unknown. Only INSERT or signal-statement can be specified after THEN.

So, DELETE command cannot be used if NOT MATCHED condition was executed. You might need to execute separate query to remove data that does not match merge condition.

Evgeny Semionov
  • 323
  • 2
  • 9