Using triggers to track user activity

I had a request to identify which user was updating the rows in a table. I created the below to triggers to track the insert and update activity back to a user:

For the update I could use a no cascade before trigger without any where condition:

  CREATE TRIGGER                                           
    SCHEMA_NAME.TRG47603                                           
      NO CASCADE BEFORE  UPDATE                             
    ON OWNER.TABLE_NAME                                    
      REFERENCING                                           
       OLD AS BEF                                           
       NEW AS AFT                                           
      FOR EACH ROW                                          
      MODE DB2SQL                                           
BEGIN ATOMIC SET C_LAST_ID  = USER 
; END     
#

For the insert I had to use an after trigger with a where condition matching on the unique index of the table:

  CREATE TRIGGER                                           
    SCHEMA_NAME.TRG47604
         AFTER  INSERT
    ON OWNER.TABLE_NAME
         REFERENCING
          NEW AS AFT
         FOR EACH ROW
      MODE DB2SQL
BEGIN ATOMIC
   UPDATE  OWNER.TABLE_NAME
      SET  C_LAST_ID   = USER 
   WHERE   C_SOURCE_ID = AFT.C_SOURCE_ID
     AND   C_SUB_ID    = AFT.C_SUB_ID
; END
#

Author: Dean Capps

Database consultant at Amazon Web Services.