Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORACLE Trigger INSERT On UPDATE

All, I am just trying to create a trigger that will pick a whole record from TABLE EMP and insert it in TABLE EMP_ARCHIVE on an UPDATE attempt (As the name suggests, EMP_ARCHIVE Table is just a history table to store the changes made on the mail EMP Table). Both table has the same fields/columns. Following is the trigger i am trying to create. I know there is something wrong but couldn't figure out. It throws error at the '(' following the INSERT command. Any help would be appreciated. Forgive me if there's some fundamental error as i am a newbie to these.

CREATE OR REPLACE TRIGGER Save_EMP_Changes
BEFORE UPDATE ON EMP
FOR EACH ROW
BEGIN
   INSERT INTO EMP_ARCHIVE
   (
      emp_id, emp_name,
      emp_age, emp_sex,
      emp_active
   )
   SELECT 
      :old.emp_id, :old.emp_name,
      :old.emp_age, :old.emp_sex,
      :old.emp_active
   FROM EMP 
   WHERE emp_id = :old.emp_id
END;
like image 451
Dine Avatar asked Apr 13 '26 16:04

Dine


1 Answers

No need to select from the table:

CREATE OR REPLACE TRIGGER Save_EMP_Changes
BEFORE UPDATE ON EMP
FOR EACH ROW
BEGIN
   INSERT INTO EMP_ARCHIVE
   (
      emp_id, emp_name,
      emp_age, emp_sex,
      emp_active
   )
   VALUES
   (  :old.emp_id, :old.emp_name,
      :old.emp_age, :old.emp_sex,
      :old.emp_active
   );
END;

Btw: in Oracle 11 you can completely automate this by create an FLASHBACK ARCHIVE for those tables. No trigger or any other hassle.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!