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

后端 未结 12 1629
南旧
南旧 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:06

    Copy & paste example for upserting one table into another, with MERGE:

    CREATE GLOBAL TEMPORARY TABLE t1
        (id VARCHAR2(5) ,
         value VARCHAR2(5),
         value2 VARCHAR2(5)
         )
      ON COMMIT DELETE ROWS;
    
    CREATE GLOBAL TEMPORARY TABLE t2
        (id VARCHAR2(5) ,
         value VARCHAR2(5),
         value2 VARCHAR2(5))
      ON COMMIT DELETE ROWS;
    ALTER TABLE t2 ADD CONSTRAINT PK_LKP_MIGRATION_INFO PRIMARY KEY (id);
    
    insert into t1 values ('a','1','1');
    insert into t1 values ('b','4','5');
    insert into t2 values ('b','2','2');
    insert into t2 values ('c','3','3');
    
    
    merge into t2
    using t1
    on (t1.id = t2.id) 
    when matched then 
      update set t2.value = t1.value,
      t2.value2 = t1.value2
    when not matched then
      insert (t2.id, t2.value, t2.value2)  
      values(t1.id, t1.value, t1.value2);
    
    select * from t2
    

    Result:

    1. b 4 5
    2. c 3 3
    3. a 1 1

提交回复
热议问题