如何在PL / SQL中捕获约束违规?

时间:2014-04-23 08:45:34

标签: sql oracle plsql constraints check-constraint

CREATE TABLE LOCATION (
  LOCID VARCHAR2(5)
, MINQTY    NUMBER
, MAXQTY    NUMBER
, PRIMARY KEY   (LOCID)
, CONSTRAINT CHECK_LOCID_LENGTH CHECK (LENGTH(LOCID) = 5)
, CONSTRAINT CHECK_MINQTY_RANGE CHECK (MINQTY BETWEEN 0 AND 999)
, CONSTRAINT CHECK_MAXQTY_RANGE CHECK (MAXQTY BETWEEN 0 AND 999)
, CONSTRAINT CHECK_MAXQTY_GREATER_MIXQTY CHECK (MAXQTY >= MINQTY)
);


CREATE OR REPLACE PROCEDURE ADD_LOCATION_TO_DB(ploccode VARCHAR2, pminqty NUMBER, pmaxqty NUMBER) AS
BEGIN
INSERT INTO location(locid, minqty, maxqty) VALUES (ploccode, pminqty, pmaxqty);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
RAISE_APPLICATION_ERROR(-20081, 'Duplicate Location ID');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20086,sqlerrm);
END;

我用约束创建了上面的表。 现在我想通过在异常中捕获它们来测试PL / SQL过程中的这些约束。但我很困惑如何去做。

1 个答案:

答案 0 :(得分:12)

违反检查约束时发生的错误是ORA-02290。虽然没有“标准”定义,但是很容易声明自己的异常,因此你可以在抛出它时捕获-2290。假设我们创建了一个如下表格:

CREATE TABLE SOME_TABLE (COL1 CHAR(1) CHECK(COL1 IN ('Y', 'N')));

然后我们运行以下块:

DECLARE
  -- First, declare and initialize an appropriate exception

  CHECK_CONSTRAINT_VIOLATED EXCEPTION;
  PRAGMA EXCEPTION_INIT(CHECK_CONSTRAINT_VIOLATED, -2290);
BEGIN
  INSERT INTO SOME_TABLE(COL1) VALUES ('X');  -- will violate the check constraint
  RETURN;
EXCEPTION
  WHEN CHECK_CONSTRAINT_VIOLATED THEN  -- catch the ORA-02290 exception
    DBMS_OUTPUT.PUT_LINE('INSERT failed due to check constraint violation');
  WHEN OTHERS THEN                     -- catch all other exceptions
    DBMS_OUTPUT.PUT_LINE('Something else went wrong - ' || SQLCODE ||
                         ' : ' || SQLERRM);
END;

如果您创建如前所示的表,然后运行上面的块,您将发现“由于检查约束违规而导致INSERT失败”行将显示在DBMS_OUTPUT上。

分享并享受。