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

前端 未结 4 1500
心在旅途
心在旅途 2021-02-05 12:59

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

However, when an item

4条回答
  •  遥遥无期
    2021-02-05 13:40

    MERGE INTO target
    USING
    (
        --Source data
        SELECT id, some_value, 0 deleteMe FROM source
        --And anything that has been deleted from the source
        UNION ALL
        SELECT id, null some_value, 1 deleteMe
        FROM
        (
            SELECT id FROM target
            MINUS
            SELECT id FROM source
        )
    ) source
       ON (target.ID = source.ID)
    WHEN MATCHED THEN
        --Requires a lot of ugly CASE statements, to prevent updating deleted data
        UPDATE SET target.some_value =
            CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
        ,isDeleted = deleteMe
    WHEN NOT MATCHED THEN
        INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)
    
    --Test data
    create table target as
    select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
    select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;
    
    create table source as
    select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
    select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;
    
    
    --Results:
    select * from target;
    
    ID  SOME_VALUE   ISDELETED
    1   new value 1  0
    2   old value 2  1
    3   new value 3  0
    

提交回复
热议问题