在psql中捕获约束违规

luk*_*uke 7 plsql

我正在使用sql developer,并在我的一个表中添加了一个约束.

constraint valid_gender check(gender in ('M','F','I','T'))
Run Code Online (Sandbox Code Playgroud)

当我尝试使用plsql过程为性别添加一个说'x'的条目时,它会因约束违规而失败(应该如此).

我想在plsql过程中添加一个"Catch",这样如果valid_gender被声音化,我可以特定于它的raise_application_error.这可能吗?

Ton*_*ews 8

甲骨文将提出一个例外情况:

ORA-02290:违反了检查约束(yourschema.valid_gender)

您可以在异常处理程序中捕获它,并使用raise_application_error几种方式引发您自己的异常.

1)你可以像这样专门捕获ORA-02290异常:

declare
  e_check_violated exception
  pragma exception_init (e_check_violated, -2290);
begin
  insert ...
exception
  when e_check_violated then
    if sqlerrm like '%(yourschema.valid_gender)%' then
       raise_application_error(-20001,'Invalid gender');
    else
      raise;
    end if;
end;
Run Code Online (Sandbox Code Playgroud)

2)您可以捕获所有异常并检查它们:

begin
  insert ...
exception
  when others then
    if sqlerrm like 'ORA-02290:%(yourschema.valid_gender)%' then
       raise_application_error(-20001,'Invalid gender');
    else
      raise;
    end if;
end;
Run Code Online (Sandbox Code Playgroud)

在大型应用程序中,通常有一个异常处理过程来概括它并在表中查找特定于约束的消息.