创建一个名为products_before_update的触发器,该触发器检查Products表的discount_percent列的新值。如果折扣百分比大于100或小于0,则此触发器应引发适当的错误。 如果新的折扣百分比在0到1之间,则此触发器应通过将新的折扣百分比乘以100来修改新的折扣百分比。这样,.2的折扣百分比将变为20。 使用适当的UPDATE语句测试此触发器。
如果语句不起作用,或者我收到消息说表正在突变,那么触发器就看不到它。
connect mgs/mgs;
CREATE or replace TRIGGER products_before_update
BEFORE UPDATE ON Products
FOR EACH ROW IS
BEGIN
IF :NEW.discount_percent > 100 THEN
RAISE_APPLICATION_ERROR(-20001, 'the discount percent cannot be greater than 100.');
ELSEIF :new.discount_percent < 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'the discount percent cannot be less than 0.');
ELSEIF :NEW.discount_percent < 1 THEN
SET :NEW.discount_percent = (:NEW.discount_percent * 100);
END IF;
END;
/
SET SERVEROUTPUT ON;
UPDATE Products
SET discount_percent = .4
WHERE product_id = 3;
我希望收到一条消息,当它处于(0; 1)时,其值超出[0,100]或更新的值,但是触发器在任何情况下都不会响应。
答案 0 :(得分:0)
这是一个有效的示例。看看。
首先测试用例:
SQL> create table products (product_id number, discount_percent number);
Table created.
SQL> insert into products values (12345, null);
1 row created.
SQL> create or replace trigger trg_prod_bu
2 before update on products
3 for each row
4 begin
5 if :new.discount_percent > 100 then
6 raise_application_error(-20001, 'can not be greater than 100');
7 elsif :new.discount_percent < 0 then
8 raise_application_error(-20002, 'can not be less than 0');
9 elsif :new.discount_percent < 1 then
10 :new.discount_percent := :new.discount_percent * 100;
11 end if;
12 end;
13 /
Trigger created.
SQL>
测试:
SQL> update products set discount_percent = -2;
update products set discount_percent = -2
*
ERROR at line 1:
ORA-20002: can not be less than 0
ORA-06512: at "SCOTT.TRG_PROD_BU", line 5
ORA-04088: error during execution of trigger 'SCOTT.TRG_PROD_BU'
SQL> update products set discount_percent = 120;
update products set discount_percent = 120
*
ERROR at line 1:
ORA-20001: can not be greater than 100
ORA-06512: at "SCOTT.TRG_PROD_BU", line 3
ORA-04088: error during execution of trigger 'SCOTT.TRG_PROD_BU'
SQL> update products set discount_percent = 15;
1 row updated.
SQL> update products set discount_percent = 0.2;
1 row updated.
SQL> select * From products;
PRODUCT_ID DISCOUNT_PERCENT
---------- ----------------
12345 20
SQL>