Search code examples
firebirddatabase-trigger

Firebird after insert trigger - insert a timestamp to inserted row


I have a field which is "timestamp" type, called "inserted_when". How can I update this field (insert a timestamp) after insert (so it only applies to selected inserted record) ? By means of a trigger of course... edit :

I tried this but cant seem to make uncommented part to work.

SET TERM ^ ;
CREATE TRIGGER AFTER_INSERT FOR MYTABLE
ACTIVE AFTER INSERT POSITION 1
AS
BEGIN
      UPDATE MYTABLE 
      SET MYTABLE.inserted_when = current_timestamp;

   ---- where mytable.ID = Inserted.ID
END^

SET TERM ; ^

Solution

  • To update the record being inserted, you need to use a BEFORE INSERT trigger, not an AFTER INSERT trigger. The values of the row to be inserted can be accessed (and updated) through the NEW context variable (there is also an OLD context variable, but that isn't relevant in a insert trigger). Note that Firebird triggers fire per row.

    So you need to change your trigger to:

    CREATE TRIGGER BEFORE_INSERT_MYTABLE FOR MYTABLE
    ACTIVE BEFORE INSERT
    AS
    BEGIN
          NEW.inserted_when = current_timestamp;
    END
    

    Note that the OLD context variable is never modifiable, and the NEW context variable is only modifiable in a BEFORE trigger.