Oracle merge constants into single table

后端 未结 3 1547
攒了一身酷
攒了一身酷 2021-02-01 06:25

In Oracle, given a simple data table:

create table data (
    id       VARCHAR2(255),
    key      VARCHAR2(255),
    value    VARCHAR2(511));

相关标签:
3条回答
  • 2021-02-01 06:50

    I would hide the MERGE inside a PL/SQL API and then call that via JDBC:

    data_pkg.merge_data ('someid', 'testKey', 'someValue');
    

    As an alternative to MERGE, the API could do:

    begin
       insert into data (...) values (...);
    exception
       when dup_val_on_index then
          update data
          set ...
          where ...;
    end;
    
    0 讨论(0)
  • 2021-02-01 06:57

    I prefer to try the update before the insert to save having to check for an exception.

    update data set ...=... where ...=...;
    
    if sql%notfound then
    
        insert into data (...) values (...);
    
    end if;
    

    Even now we have the merge statement, I still tend to do single-row updates this way - just seems more a more natural syntax. Of course, merge really comes into its own when dealing with larger data sets.

    0 讨论(0)
  • 2021-02-01 06:59

    I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like:

    merge into data
    using (
        select
            'someid' id,
            'testKey' key,
            'someValue' value
        from
            dual
    ) val on (
        data.id=val.id
        and data.key=val.key
    )
    when matched then 
        update set data.value = val.value 
    when not matched then 
        insert (id, key, value) values (val.id, val.key, val.value);
    
    0 讨论(0)
提交回复
热议问题