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

Plsql 违反PL/SQL约束时显示自定义消息,plsql,constraints,custom-exceptions,Plsql,Constraints,Custom Exceptions,我正在编写一个pl/sql过程。我有一个列上的约束,它不允许值小于0和大于500。如果违反此约束(例如“ID超出范围”),我需要显示一条自定义消息。目前这是一个例外,也是getting中的输出。还有另一个过程输出错误,因此使用raise_application_error 例外情况 when VALUE_ERROR then raise_application_error(-20002, 'Customer ID out of range'); 错误消息 "ORA-20000: ORA-022

我正在编写一个pl/sql过程。我有一个列上的约束,它不允许值小于0和大于500。如果违反此约束(例如“ID超出范围”),我需要显示一条自定义消息。目前这是一个例外,也是getting中的输出。还有另一个过程输出错误,因此使用raise_application_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;
打开服务器输出;
---------------------------------------------------------------
更改表格客户
添加约束检查id检查范围
检查(custid>0且custid<500);
---------------------------------------------------------------
创建或替换过程将客户添加到数据库(pcustid编号,pcustname varchar2),如下所示
开始
插入客户
值(pcustid,pcustname,0,'OK');
例外
当DUP_VAL_在索引上时
引发应用程序错误(-20001,“重复客户ID”);
当值出现错误时,则
引发应用程序错误(-20002,“客户ID超出范围”);
当其他人
引发应用程序错误(-20000,SQLERRM);
结束;

谢谢

我猜您收到了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\u INIT
调用中,而不是-2290


分享并享受。

那么您的问题到底是什么?错误消息输出不是我想要的。因此,我假设我的异常(当前值_ERROR)需要更改为其他内容,以便显示自定义错误消息。我只是不知道应该发生什么异常,因为我收到一个编译错误,说必须声明违反了echeck_约束。我尝试过复制您的代码,但没有成功。请将异常声明移动到过程中,如上图所示,或者创建一个包来保存您的异常声明和初始化。分享和享受。