在psql中捕获约束违规

时间:2011-08-28 12:14:55

标签: plsql

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

constraint valid_gender check(gender in ('M','F','I','T'))

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

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

3 个答案:

答案 0 :(得分:8)

Oracle将提出一个例外说明:

  

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;

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;

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

答案 1 :(得分:0)

你可以先测试一下:

if gender_value not in ('M','F','I','T') then
    raise_application_error...
end if;

答案 2 :(得分:0)

在代码中使用匿名阻止...

  BEGIN
    INSERT or update...

    EXCEPTION
    WHEN dup_val_on_index THEN
    RISE...

    END;