【问题标题】:How to create a trigger to check an updated field value如何创建触发器以检查更新的字段值
【发布时间】:2019-09-08 05:56:09
【问题描述】:

创建一个名为 products_before_update 的触发器,用于检查 Products 表的 discount_percent 列的新值。如果折扣百分比大于 100 或小于 0,则此触发器应引发适当的错误。 如果新的折扣百分比介于 0 和 1 之间,则此触发器应修改新的折扣百分比,将其乘以 100。这样,0.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) 中更新值,但触发器在任何情况下都不会做出反应。

【问题讨论】:

  • 删除ISELSEIF 应该是ELSIF 而不是SET &lt;lvalue&gt; = &lt;rvalue&gt; 用于赋值,例如在SQL Server 中使用,使用&lt;lvalue&gt; := &lt;rvalue&gt;
  • 顺便说一句,你可以避开触发器。第一个和第二个IF 条件可以转换为check constraint,第三个可能转换为虚拟列..?

标签: oracle plsql oracle12c database-trigger


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多