如何捕获约束违规并在PL / SQL中给出用户定义的错误消息?

时间:2018-10-03 10:03:13

标签: sql oracle

当违反检查约束时,如何在PL / SQL中提供用户定义的错误消息?

      CREATE TABLE "AP"."SOURCE" 
      (
        ,"RATING" CHAR(30 BYTE)
        ,"SUBMISSION_STATUS" CHAR(12 BYTE)
        ,"UOANAME" CHAR(32 BYTE)
        ,"W_INSERT_DT" TIMESTAMP (6)
        ,"W_UPDATE_DT" TIMESTAMP (6)
        ,"SCIVAL_CIT_CATEGORY" NUMBER(5,0)
        ,"TOTAL_AUTHORS" BINARY_DOUBLE
        ,"REF2014" CHAR(3 BYTE)
      CONSTRAINT "Submission_Rating_not_valid" 
      CHECK ( Submission_status ='To be scored' 
            and Rating is null  
            or Submission_status ='NO' 
            and Rating is null
            or Submission_status = 'Potential'
            and Rating is not null 
            and Rating != 'Not REF Eligible'              
            or  Submission_status ='Yes'
            and Rating is not null
            and Rating != 'Not REF Eligible'
            or  Submission_status ='No'
            and Rating is not null 
            and Rating != 'Not REF Eligible'
            or  Submission_status ='No'
            and Rating = 'Not REF Eligible'*) ENABLE
       )

2 个答案:

答案 0 :(得分:2)

在PL / SQL中,有一个EXCEPTION关键字来处理这些异常。

EXCEPTION 

然后,您可以在PL / SQL块中设置如果执行PL / SQL代码引发特定异常该怎么办。

WHEN <name of the exception> THEN <statements to handle it>;

如果您需要所有未提及的异常的后备,请使用OTHERS:

WHEN OTHERS THEN <statements to handle it>;

要使用自定义错误文本为用户引发自定义异常,请使用RAISE_APPLICATION_ERROR。

示例:

CREATE OR REPLACE PROCEDURE "APEXDEV01"."ADD_OMT_SOURCE" (
  rating VARCHAR2, 
  submission_status VARCHAR2, 
  uoaname VARCHAR2, 
  scival_cit_category NUMBER,
  total_authors BINARY_DOUBLE,
  selfselected VARCHAR2,
  ref2014 VARCHAR2)
AS
BEGIN
  INSERT INTO "APEXDEV01"."OMT_SOURCE" VALUES (
    rating, submission_status, uoaname, SYSDATE, SYSDATE, 
    scival_cit_category, total_authors, selfselected, ref2014);
  EXCEPTION
    WHEN "Submission_Rating_not_valid" THEN
      RAISE_APPLICATION_ERROR(-20081, "Submission rating not valid");
    WHEN OTHERS THEN
      RAISE_APPLICATION_ERROR(-20086,sqlerrm);
END;
/ 

还值得一提的是,您的DDL语句中的条件组合了AND和OR,并且应该使用一些括号来管理它们,以免其逻辑混乱和混乱。

答案 1 :(得分:0)

您需要一个括号,并为and或条件使用单独的括号

company.com

companya.com