Pages

Sunday, September 18, 2011

Triggers in pl/sql

Similar to :before, :after filters that are in ruby on rails, triggers in pl/sql are there to perform operations when certain events occur. This still sounds vague.

Take for example, we have a customer db table.

It would be helpful for us to have a trigger which runs when a deletion, insertion, update or  update on certain columns occurs to the customer db table. A typical action would be to log each action, timestamp and a comment into an audit dbtable for audit purposes to track the changes to the customer db table.

Format/syntax:

CREATE [OR REPLACE] TRIGGER <trigger name>
  {BEFORE|AFTER}
  {INSERT|UPDATE|DELETE| UPDATE OF <column list> ON <desired db table's name>
  [FOR EACH ROW]

  [WHEN  .... ] -- this is where we place more filters if we want the trigger to go to work when either an insertion/deletion/update or update on certain columns of a db table. For example, we only want to have the trigger work on Deletion statements issued on customer records for  customers who reside in 'state' = 'Melbourne, Victoria, Australia'
  [DECLARE]
      -- fit all the declaration statements here
  BEGIN

   [EXCEPTION]
 
END <trigger name>;