Create a trigger named products_before_update that checks the new value for the discount_percent column of the Products table. This trigger should raise an appropriate error if the discount percent is greater than 100 or less than 0. If the new discount percent is between 0 and 1, this trigger should modify the new discount percent by multiplying it by 100. That way, a discount percent of .2 becomes 20. Test this trigger with an appropriate UPDATE statement.
Either if statement doesn't work or I am getting message that table is mutating, so the trigger can't see it..
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;
I expect a message then a value is out of [0,100] or updated value when it was in (0;1), but the trigger doesn't react in any case.
Here's an example which works. Have a look.
Test case first:
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>
Testing:
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>