----------------------------------------------------------------
- PL/SQL: Trigger example (Example 4.5.1)                      -
- Chapter 4; Oracle Programming -- A Primer                    -
-            by R. Sunderraman                                 -
----------------------------------------------------------------

CREATE OR REPLACE TRIGGER insert_odetails
BEFORE INSERT ON odetails
FOR EACH ROW 
DECLARE my_qoh parts.qoh%type; 
        my_olevel parts.olevel%type;
        out_of_stock EXCEPTION;
BEGIN
  select qoh, olevel 
  into   my_qoh, my_olevel 
  from   parts 
  where  parts.pno = :new.pno;

  if (:new.qty < my_qoh) then
    update parts 
    set    qoh = qoh - :new.qty
    where  parts.pno = :new.pno;
    if ((my_qoh - :new.qty) < my_olevel) then
       update parts
       set    qoh = olevel * 5
       where  parts.pno = :new.pno;
       insert into restock values (sysdate,:new.pno);
--       DBMS_OUTPUT.PUT_LINE('Added row to RESTOCK TABLE');
    end if;
  else
    RAISE out_of_stock;
 end if;

EXCEPTION
  WHEN out_of_stock THEN
--    DBMS_OUTPUT.PUT_LINE('Ordered quantity more than what is in stock');
-- error number should be between -20000 and -20999
    RAISE_APPLICATION_ERROR(-20001,'CANNOT ADD THIS ODETAILS ROW');
END;
/
