Oracle: how to UPSERT (update or insert into a table?)

后端 未结 12 1377
南旧
南旧 2020-11-22 07:18

The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:

if table t has a row exists          


        
12条回答
  •  隐瞒了意图╮
    2020-11-22 08:16

    I've been using the first code sample for years. Notice notfound rather than count.

    UPDATE tablename SET val1 = in_val1, val2 = in_val2
        WHERE val3 = in_val3;
    IF ( sql%notfound ) THEN
        INSERT INTO tablename
            VALUES (in_val1, in_val2, in_val3);
    END IF;
    

    The code below is the possibly new and improved code

    MERGE INTO tablename USING dual ON ( val3 = in_val3 )
    WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
    WHEN NOT MATCHED THEN INSERT 
        VALUES (in_val1, in_val2, in_val3)
    

    In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could have execute the correct insert or update with a single index lookup.

    I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.

提交回复
热议问题