在下面的触发器中,使用duplicate_info异常而不在开始块内提升它,我不确定这是如何工作的。其他人也没有例外但是这个duplicate_info异常有效。奇怪!
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;
/
答案 0 :(得分:2)
当违反主要或唯一约束时,Oracle会引发错误:
ORA-00001:违反了唯一约束( schemaname.constraintname )
触发器已定义异常duplicate_info
,然后通过编译指示将其与ORA-00001错误相关联:
PRAGMA EXCEPTION_INIT (duplicate_info, -00001);
因此,这意味着当Oracle引发错误ORA-00001时,会引发相关的用户定义异常duplicate_info
。
但这非常多余,因为Oracle已经为ORA-00001提供了一个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;