insert if not exists oracle

后端 未结 10 2073
天命终不由人
天命终不由人 2020-12-07 23:08

I need to be able to run an Oracle query which goes to insert a number of rows, but it also checks to see if a primary key exists and if it does, then it skips that insert.

10条回答
  •  执笔经年
    2020-12-07 23:36

    Coming late to the party, but...

    With oracle 11.2.0.1 there is a semantic hint that can do this: IGNORE_ROW_ON_DUPKEY_INDEX

    Example:

    insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(customer_orders,pk_customer_orders) */
      into customer_orders
           (order_id, customer, product)
    values (    1234,     9876,  'K598')
         ;
    

    UPDATE: Although this hint works (if you spell it correctly), there are better approaches which don't require Oracle 11R2:

    First approach—direct translation of above semantic hint:

    begin
      insert into customer_orders
             (order_id, customer, product)
      values (    1234,     9876,  'K698')
      ;
      commit;
    exception
      when DUP_VAL_ON_INDEX
      then ROLLBACK;
    end;
    

    Second aproach—a lot faster than both above hints when there's a lot of contention:

    begin
        select count (*)
        into   l_is_matching_row
        from   customer_orders
        where  order_id = 1234
        ;
    
        if (l_is_matching_row = 0)
        then
          insert into customer_orders
                 (order_id, customer, product)
          values (    1234,     9876,  'K698')
          ;
          commit;
        end if;
    exception
      when DUP_VAL_ON_INDEX
      then ROLLBACK;
    end;
    

提交回复
热议问题