【发布时间】:2016-04-13 10:11:16
【问题描述】:
我有一个在表格中插入一行的过程。我做了各种检查,如果一切都通过了,它会在表格中插入一行。
其中一项检查是检查表中是否已存在具有主键的行。如果具有主键的行已经存在,则该过程应该能够捕获它并引发错误。
最好的方法是什么?
【问题讨论】:
标签: sql oracle stored-procedures plsql
我有一个在表格中插入一行的过程。我做了各种检查,如果一切都通过了,它会在表格中插入一行。
其中一项检查是检查表中是否已存在具有主键的行。如果具有主键的行已经存在,则该过程应该能够捕获它并引发错误。
最好的方法是什么?
【问题讨论】:
标签: sql oracle stored-procedures plsql
与其手动检查主键冲突,不如让 Oracle 为您处理。如果您尝试插入到表中,并且发现主键冲突,Oracle 将引发“dup_val_on_index”异常。例如:
declare
begin
--try and insert a value into the table
insert into my_table (
id,
description
) values (
1,
'a duplicate id'
);
exception
when dup_val_on_index then
dbms_output.put_line('a duplicate primary key');
--your error handling logic here
raise; --optionally re-raise the exception
end;
【讨论】: