tags:

views:

498

answers:

3

I'm adding a column tsu (timestamp update) of type DATETIME to a number of my tables.

I need to write BEFORE UPDATE triggers that will update the column to CURRENT_TIMESTAMP(), but I can't get it right. Tried:

DELIMITER $$
CREATE
    TRIGGER `cams`.`tsu_update_csi` BEFORE UPDATE
    ON `cams`.`csi`
    FOR EACH ROW BEGIN
        UPDATE csi SET tsu = CURRENT_TIMESTAMP WHERE csi_code = OLD.csi_code;
    END$$
DELIMITER ;

Can anyone point me in the right direction pls? MTIA

+1  A: 

If the field can be defined as a timestamp, you can use the following:

ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
              ON UPDATE CURRENT_TIMESTAMP);
Zerofiz
No, I can't do that, if I keep the original `ts` column:` ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP`
maxhugen
+1  A: 

Don't know if it'll work for you, but you can always make it a TIMESTAMP field with no default value -- MySQL will automatically set the value of the first such field defined in the table to the current timestamp on every update.

Ian Clelland
Thanks Zerofiz and Ian. I already have a column `ts` which is set to default CURRENT_TIMESTAMP, as it was intended to represent the "Date Created". From my reading up on TIMESTAMP, it's not possible to use CURRENT_TIMESTAMP as default on one ts column and on update in another column (which is exactly what I really wanted of course).I'm checking with the client to see if we can use the existing `ts` field as the "Date Updated", and dispense with the "Date Created".
maxhugen
+1  A: 

Okay, try this one:

DELIMITER $$ CREATE  
    TRIGGER `cams`.`tsu_update_csi` BEFORE UPDATE  
    ON `cams`.`csi`  
      FOR EACH ROW BEGIN  
        SET NEW.tsu = CURRENT_TIMESTAMP;   
END$$ DELIMITER ;
Zerofiz
Thanks, that example is what I needed! Understand TIMESTAMP much better now.
maxhugen