Oracle DB insert and do nothing on duplicate key

柔情痞子 提交于 2019-12-11 02:09:09

问题


I have to insert some data in oracle DB, without previously checking if it already exist.

Does exist any way, transiction on oracle to catch the exception inside the query and handle it to don't return any exception?

It would be perfect something in mysql's style like

insert .... on duplicate key a=a

回答1:


You can use MERGE. The syntax is a bit different from a regular insert though;

MERGE INTO test USING (
  SELECT 1 AS id, 'Test#1' AS value FROM DUAL    -- your row to insert here
) t ON (test.id = t.id)                          -- duplicate check
WHEN NOT MATCHED THEN 
   INSERT (id, value) VALUES (t.id, t.value);    -- insert if no duplicate

An SQLfiddle to test with.




回答2:


If you can use PL/SQL, and you have a unique index on the columns where you don't want any duplicates, then you can catch the exception and ignore it:

begin
   insert into your_table (your_col) values (your_value);
exception
   when dup_val_on_index then null;
end;


来源:https://stackoverflow.com/questions/17946595/oracle-db-insert-and-do-nothing-on-duplicate-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!