DB2 v9.5 Trigger Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • David Robertson
    New Member
    • Jan 2011
    • 1

    DB2 v9.5 Trigger Question

    Hello,

    I have a request that I thought was straightforward and would be fairly simple. After many hours of research and trying various triggers, procedures and variables, I have not been able to find a solution.

    I need to evaluate a timestamp column to be in an acceptable range on insert/update of a table. If the value is out of the acceptable range, I need to update it to an acceptable value and then write a record into an audit table recording the change.

    I began with a BEFORE INSERT trigger, added a WHEN condition and SET the value, no problem, but I cannot insert a new record into another table in a BEFORE trigger. So, I wrote 2 triggers, SET the timestamp in the BEFORE trigger, and INSERT the audit record in the AFTER trigger. This does not work because the WHEN condition in the AFTER trigger fails because the BEFORE trigger has modified the value so I do not know when I need to write the audit record.

    I then tried moving the INSERT into a DB2 procedure that I called from the BEFORE trigger, but I learned you cannot call a procedure with 'MODIFIES SQL DATA' from a BEFORE trigger.

    Back to the drawing board,my latest attempt is creating a GLOBAL VARIABLE that is SET in the BEFORE trigger that I can then evaluate in the AFTER trigger WHEN condition to know when to write the audit record. I have not been able to SET the GLOBAL VARIABLE in the BEFORE trigger, I get a -20430 SQLCODE "A global variable cannot be set or applied in this context."

    I am running out of ideas on how to accomplish this. Conceptually it seems to be simple.

    Here is the latest trigger / global variable statement I have:

    CREATE VARIABLE gv_BLOCK_EFFDAT E_ADJUST_DATE TIMESTAMP
    DEFAULT CURRENT TIMESTAMP;

    CREATE TRIGGER "BLOCK_BI_EFFDA TE_ADJ"
    NO CASCADE BEFORE INSERT
    ON ADJ
    REFERENCING
    NEW AS "N"
    FOR EACH ROW
    WHEN (N.EFF_DATE < (SELECT MIN(E.EFF_DATE) FROM "DATE_CUTOF F" )
    BEGIN ATOMIC
    SET gv_BLOCK_EFFDAT E_ADJ_DATE = N.EFFDATE;
    SET (N.EFF_DATE) = (SELECT MIN(E.EFF_DATE)
    FROM "DATE_CUTOF F" );
    END;

    CREATE TRIGGER "BLOCK_AI_EFFDA TE_ADJ"
    AFTER INSERT
    ON ADJ
    REFERENCING
    NEW AS "N"
    FOR EACH ROW
    WHEN (gv_BLOCK_EFFDA TE_ADJ_DATE < (SELECT MIN
    (E.EFF_DATE) FROM "DATE_CUTOF F" ))
    BEGIN ATOMIC
    INSERT INTO NOTES
    (RECORD_DATE,US ER_ID,ROWID,COM MENT,TRANMEMO)
    VALUES( CURRENT TIMESTAMP,USER_ ID,NEXTVAL FOR
    SEQ_NOTES),'SYS TEM MODIFIED EFFDATE', ' THE
    SYSTEM MODIFIED THE EFFECTIVE DATE TO BE EQUAL
    TO THE INCEPTION DATE.');
    END;

    COMMIT;


    Any advice or ideas will be greatly appreciated!!
Working...