Google Analytics

Pages

Monday, May 03, 2010

mysql triggers

Mysql triggers can help keeping your code clean and simple. Some application logic can be stored directly into the mysql engine, and here is an example I have used recently:

I have got 2 correspondence tables, refering to the same object, but representing 2 different interface implementations.

What I want is that when a record is added in 1 table, it also creates a corresponding record in the other table. Here is how to do it with a simple trigger (I have added a test on the status column, to make the insert conditional):

DELIMITER $$

DROP TRIGGER /*!50033 IF EXISTS */ `mytrigger`$$

CREATE TRIGGER `mytrigger` BEFORE INSERT on `table1
FOR EACH ROW

BEGIN
    IF NEW.STATUS = "new" THEN
              INSERT INTO table2 (MY_ID, STATUS, CREATED_AT) VALUES (NEW.MY_ID, NEW.STATUS, NOW());
          END IF;
END$$

DELIMITER ;
.

0 comments:

Share it