如何创建触发器以检查更新的字段值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何创建触发器以检查更新的字段值相关的知识,希望对你有一定的参考价值。
创建名为products_before_update的触发器,该触发器检查Products表的discount_percent列的新值。如果折扣百分比大于100或小于0,则此触发器应引发适当的错误。如果新折扣百分比介于0和1之间,则此触发器应通过将其折叠为100来修改新折扣百分比。这样,折扣.2的百分比变为20.使用适当的UPDATE语句测试此触发器。
if语句不起作用或者我收到表正在变异的消息,因此触发器无法看到它。
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,100]或更新值,当它在(0; 1)时,但触发器在任何情况下都没有反应。
答案
这是一个有效的例子。看一看。
测试用例首先:
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>
以上是关于如何创建触发器以检查更新的字段值的主要内容,如果未能解决你的问题,请参考以下文章
如何创建触发器以将值插入到插入时为 Max([ID Field])+1 的 ID 字段中
当同一转发器字段的值以其他语言更新时,ACF 转发器字段中的值是不是为空?