【问题标题】:In oracle procedure, check if the row with primary key exists, if key already exists raise exception在oracle程序中,检查具有主键的行是否存在,如果键已经存在引发异常
【发布时间】:2016-04-13 10:11:16
【问题描述】:

我有一个在表格中插入一行的过程。我做了各种检查,如果一切都通过了,它会在表格中插入一行。

其中一项检查是检查表中是否已存在具有主键的行。如果具有主键的行已经存在,则该过程应该能够捕获它并引发错误。

最好的方法是什么?

【问题讨论】:

    标签: sql oracle stored-procedures plsql


    【解决方案1】:

    与其手动检查主键冲突,不如让 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;
    

    【讨论】:

    • 这样您不仅可以捕获 PK 违规,还可以捕获每个违反唯一约束的情况
    • 甜蜜。这就是我一直在寻找的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多