违反约束时显示自定义消息 PL/SQL

Posted

技术标签:

【中文标题】违反约束时显示自定义消息 PL/SQL【英文标题】:Display custom message when constraint is violated PL/SQL 【发布时间】:2014-08-23 01:30:00 【问题描述】:

我正在编写一个 pl/sql 过程。我对不允许低于 0 和高于 500 的值的列设置了约束。如果违反此约束(例如“ID 超出范围”),我需要显示自定义消息。目前这是一个例外,也是获取的输出。还有另一个输出错误的过程,因此使用 raise_applcation_error。

例外

when VALUE_ERROR then
raise_application_error(-20002, 'Customer ID out of range');

错误信息

"ORA-20000: ORA-02290: check constraint (s5849497.CK_ID_RANGE) violated"

我想要什么

"ORA-20000: Customer ID out or range"

如果有帮助,这里是整个块

set serveroutput on;

---------------------------------------------------------------
alter table customer
add constraint ck_id_range
check (custid > 0 and custid < 500);
---------------------------------------------------------------

create or replace procedure ADD_CUSTOMER_TO_DB(pcustid number, pcustname varchar2) as

begin
    insert into customer
    values (pcustid,pcustname,0,'OK');
exception
when DUP_VAL_ON_INDEX then
  raise_application_error(-20001, 'Duplicate customer ID');
when VALUE_ERROR then
  raise_application_error(-20002, 'Customer ID out of range');
when others then
  raise_application_error(-20000, SQLERRM);
end;

谢谢

【问题讨论】:

那么你的问题到底是什么? 错误信息输出不是我想要的。所以我假设我的异常(当前为 VALUE_ERROR)需要更改为其他内容以显示我的自定义错误消息。我只是不知道应该是什么异常 【参考方案1】:

我猜您遇到了 ORA-02290 错误。在异常处理程序中捕获这种情况的方法是为特定错误代码(在本例中为 -2290)声明和初始化一个异常,然后在处理程序中使用您的自定义异常:

create or replace procedure ADD_CUSTOMER_TO_DB(pcustid number,
                                               pcustname varchar2)
as
  eCheck_constraint_violated  EXCEPTION;
  PRAGMA EXCEPTION_INIT(eCheck_constraint_violated, -2290);
begin
    insert into customer
    values (pcustid,pcustname,0,'OK');
exception
when DUP_VAL_ON_INDEX then
  raise_application_error(-20001, 'Duplicate customer ID');
when eCheck_constraint_violated then
  raise_application_error(-20002, 'Customer ID out of range');
when others then
  raise_application_error(-20000, SQLERRM);
end;

正如您将在上面看到的,我只是将 VALUE_ERROR 替换为新定义的异常。

如果您遇到的错误不是 -2290,只需将您看到的错误放在上面的 PRAGMA EXCEPTION_INIT 调用中,而不是 -2290。

分享和享受。

【讨论】:

我收到一个编译错误,提示必须声明 echeck_constraint_violated。我试过复制你的代码,但也没有用 将异常声明移动到过程中,如上所示,或者创建一个包来保存您的异常声明和初始化。分享和享受。

以上是关于违反约束时显示自定义消息 PL/SQL的主要内容,如果未能解决你的问题,请参考以下文章

选择表格视图单元格时显示自定义 UIImageView

打开约会项目时显示自定义任务窗格(会议发生和个人会议)

下载文件时显示自定义对话框

添加联系人时显示自定义同步适配器作为选项

仅在填充Wordpress时显示自定义字段

UILabel 在使用文本设置属性时显示自定义字体错误,但在代码中设置时工作正常