Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

I have a main database and a report database, and I need to sync a table from main into report.

However, when an item gets deleted in the main database, I only want to set an IsDeleted flag in the report database.

What is an elegant way to do this?

I'm currently using a MERGE statement, like this:

MERGE INTO report.TEST target
USING (SELECT * FROM main.TEST) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    UPDATE SET (target... = source...)
WHEN NOT MATCHED THEN
    INSERT (...) VALUES (source...)
;

The WHEN NOT MATCHED statement gives me all NEW values from main, but I also want to update all OLD values from report.

I'm using Oracle PL/SQL.

like image 650
Scott Rippey Avatar asked May 10 '12 17:05

Scott Rippey


People also ask

Which is better MERGE or update in Oracle?

merge is faster for merging. update is faster for updating.

Can we use where clause in MERGE statement in Oracle?

where_clause - You must specify the where_clause if you want Oracle to execute the update operation only if the specified condition is true. The WHERE condition can apply to either the data source or the target table. If the condition is false, the update operation is skipped when merging the row into the target table.

How does MERGE work in Oracle?

Use the MERGE statement to select rows from one or more sources for update or insertion into a table or view. You can specify conditions to determine whether to update or insert into the target table or view. This statement is a convenient way to combine multiple operations.


2 Answers

You can do it with a separate UPDATE statement

UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.

like image 197
steve godfrey Avatar answered Oct 19 '22 14:10

steve godfrey


The following answer is to merge data into same table

MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif') 
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.

like image 35
Zafrullah Syed Avatar answered Oct 19 '22 14:10

Zafrullah Syed