See website in:
DEC
13
Tip: Using Merge on Oracle

A very useful tip when you need to insert or update a large quantity of data from a a query is use merge command.

This command is simple and performing better then a cursor or a temp table (temporary table). Your execution is like a DML command (commands of insert, update or delete) so it needs a explict commit after your execution.

MERGE INTO <destination_data_table> hint1
 USING (SELECT field1, field2.....
              FROM <home_data_table>) hint2
     ON (<condition_for_comparing_data>
            hint1.field1 = hint2.field1)
  WHEN MATCHED THEN
        <when_matched_the_condition_execute_an DML_command>
        UPDATE SET hint1.field2 = hint2.field2
  WHEN NOT MATCHED THEN
       
<when_not_matched_the_condition_execute_another_DML_command>
        INSERT (hint1.field1, hint1.field2, ...)
        VALUES (
hint2.field1, hint2.field2,...);

When the condition match or not we can put any DML command. On top exemple, when condition (hint1.field1 = hint2.field1 at ON clause) match, we use an update command. When condition not match, we use an Insert.


Merge use error:

ORA-30926:  unable to get a stable set of rows in the source tables =  this occurs when the SELECT condition on USING clause returns more than a single line, aply at ON clause. On the top example, data of SELECT field1, field2..... FROM <home_data_table> doesn't bring more records estabilish on ON clause (hint1.field1 = hint2.field1)

Tags: Merge
Blog - Erika Nagamine - 2007-2012