Friday, May 6, 2016

Insert into a table if not exists

In order to make a SQL statement repeatable, you may want to avoid inserting the same value and prevent a primary key constraint error if inserting twice.

The command MERGE INTO which allows inserts and updates can also be used for insert only.

merge into table1 t1
    using (select 'value1' as value1 ,value2 as value2
           from dual) t2
    on ( t1.value1 = t2.value1)
when not matched then
   insert values (t2.value1, t2.value2)

No comments :

Post a Comment