Monday, August 9, 2010

Merge in SQL

Merge:
This article introduces the new MERGE SQL command (sometimes referred to as "UPSERT"). MERGE is a DML command that enables us to optionally update or insert data into a target table, depending on whether matching records already exist. In versions prior to 9i, we would have to code this scenario either in separate bulk SQL statements or in PL/SQL. We will compare MERGE to these methods later in this article.



MERGE INTO target_table tgt
USING source_table src
ON (src.object_id = tgt.object_id)
WHEN MATCHED
THEN
UPDATE SET
tgt.object_name = src.object_name, tgt.object_type = src.object_type
WHEN NOT MATCHED
THEN
INSERT (tgt.object_id, tgt.object_name, tgt.object_type)
VALUES (src.object_id, src.object_name, src.object_type);

1 comment:

  1. For This Statement :
    From Target and source table join must be primary key. If you have nay duplicates in Target or source table you will get a error.

    ReplyDelete