Oracle Equivalent to MySQL INSERT IGNORE?

后端 未结 8 2250
旧时难觅i
旧时难觅i 2020-11-27 07:24

I need to update a query so that it checks that a duplicate entry does not exist before insertion. In MySQL I can just use INSERT IGNORE so that if a duplicate record is fo

相关标签:
8条回答
  • 2020-11-27 07:35

    A simple solution

    insert into t1
      select from t2 
      where not exists 
        (select 1 from t1 where t1.id= t2.id)
    
    0 讨论(0)
  • 2020-11-27 07:37

    If you're on 11g you can use the hint IGNORE_ROW_ON_DUPKEY_INDEX:

    SQL> create table my_table(a number, constraint my_table_pk primary key (a));
    
    Table created.
    
    SQL> insert /*+ ignore_row_on_dupkey_index(my_table, my_table_pk) */
      2  into my_table
      3  select 1 from dual
      4  union all
      5  select 1 from dual;
    
    1 row created.
    
    0 讨论(0)
  • 2020-11-27 07:37

    I don't think there is but to save time you can attempt the insert and ignore the inevitable error:

    begin
    
       insert into table_a( col1, col2, col3 )
       values ( 1, 2, 3 );
    
       exception when dup_val_on_index then 
          null;
    
    end;
    /
    

    This will only ignore exceptions raised specifically by duplicate primary key or unique key constraints; everything else will be raised as normal.

    If you don't want to do this then you have to select from the table first, which isn't really that efficient.

    0 讨论(0)
  • 2020-11-27 07:40

    yet another "where not exists"-variant using dual...

    insert into t1(id, unique_name)
      select t1_seq.nextval, 'Franz-Xaver' from dual 
        where not exists (select 1 from t1 where unique_name = 'Franz-Xaver');
    
    0 讨论(0)
  • 2020-11-27 07:41

    How about simply adding an index with whatever fields you need to check for dupes on and say it must be unique? Saves a read check.

    0 讨论(0)
  • 2020-11-27 07:47

    This one isn't mine, but came in really handy when using sqlloader:

    1. create a view that points to your table:

      CREATE OR REPLACE VIEW test_view
      AS SELECT * FROM test_tab
      
    2. create the trigger:

      CREATE OR REPLACE TRIGGER test_trig
       INSTEAD OF INSERT ON test_view
       FOR EACH ROW
        BEGIN
         INSERT INTO test_tab VALUES
          (:NEW.id, :NEW.name);
        EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN NULL;
        END test_trig;
      
    3. and in the ctl file, insert into the view instead:

      OPTIONS(ERRORS=0)
      LOAD DATA
      INFILE 'file_with_duplicates.csv'
      INTO TABLE test_view
      FIELDS TERMINATED BY ','
      (id, field1)
      
    0 讨论(0)
提交回复
热议问题