Syntax:
MERGE INTO [catalog-name.]table-name [AS alias] USING source [AS alias] ON matching-expression merge-when-clause [merge-when-clause]* source: [catalog-name.]table-name | view-name | select-statement merge-when-clause: WHEN MATCHED [AND expression] THEN DELETE | WHEN MATCHED [AND expression] THEN UPDATE SET column = expression, [column = expression]* | WHEN NOT MATCHED [AND expression] THEN INSERT [(column[, column]*)] VALUES (expression[, expression]*)
The MERGE statement can be used to insert new records or update existing records in an existing table, depending on whether a given condition is met or not. The sorce rows to merge into the target table are established on the basis of matching-expression.
The WHEN MATCHED sub-clauses specify actions to undertake when a merged row is present in the source and destination tables. An additional condition can be specified, in this case the action will take place only when it is satisfied. The actions can be: DELETE, in which case the row is removed from the target table, or UPDATE, which results in the row from the target table being updated according to column = expression clauses.
The WHEN NOT MATCHED sub-clauses specify the action to undertake when a row from the source table is not present in the target table. An additional condition can be specified, in this case the action will take place only when its is satisfied. The only possible action is INSERT. In the inserted row each column specified after INSERT is given the corresponding value from the list after the VALUES keyword.