2017-03-01 53 views
0

在下面的觸發器中,在使用duplicate_info異常時並未在begin塊中引發它,我不確定這是如何工作的。當其他人也不例外,但是這個duplicate_info例外有效。奇怪!在Oracle觸發器中用戶定義的異常

CREATE OR REPLACE TRIGGER ORDER_INFO_T 
INSTEAD OF INSERT ON order_info 
DECLARE 
    duplicate_info EXCEPTION; 
    PRAGMA EXCEPTION_INIT (duplicate_info, -00001); 
BEGIN 
    INSERT INTO customers 
    (customer_id, cust_last_name, cust_first_name) 
    VALUES (
    :new.customer_id, 
    :new.cust_last_name, 
    :new.cust_first_name); 

    INSERT INTO orders (order_id, order_date, customer_id) 
    VALUES (
    :new.order_id, 
    :new.order_date, 
    :new.customer_id); 
EXCEPTION 
    WHEN duplicate_info THEN 
     RAISE_APPLICATION_ERROR (
     num=> -20107, 
     msg=> 'Duplicate customer or order ID'); 
END order_info_insert; 
/

回答

2

當主或唯一約束被違反,甲骨文引發錯誤:

ORA-00001: unique constraint (schemaname.constraintname) violated

觸發已經經由編譯指示所定義的例外duplicate_info,然後與ORA-00001錯誤相關聯的:

PRAGMA EXCEPTION_INIT (duplicate_info, -00001); 

所以這意味着當Oracle引發錯誤ORA-00001時,會引發相關的用戶定義異常duplicate_info

這是相當多餘的,但因爲甲骨文對ORA-00001已經提供了anexception DUP_VAL_ON_INDEX

CREATE OR REPLACE TRIGGER ORDER_INFO_T 
INSTEAD OF INSERT ON order_info 
BEGIN 
INSERT INTO customers 
(customer_id, cust_last_name, cust_first_name) 
VALUES (
:new.customer_id, 
:new.cust_last_name, 
:new.cust_first_name); 
INSERT INTO orders (order_id, order_date, customer_id) 
VALUES (
:new.order_id, 
:new.order_date, 
:new.customer_id); 
EXCEPTION 
WHEN dup_val_on_index THEN 
RAISE_APPLICATION_ERROR (
num=> -20107, 
msg=> 'Duplicate customer or order ID'); 
END order_info_insert;