You are on page 1of 2

# Example 2: Automatically keep track of edits to the 'members' table above.

# We define three TRIGGERs on 'member' to keep records of # INSERT, UPDATE, and DELETE actions. CREATE TABLE member_audit_trail( event_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, id SMALLINT UNSIGNED DEFAULT NULL, old_name VARCHAR(32) DEFAULT NULL, action ENUM('insert', 'update', 'delete') NOT NULL, name VARCHAR(32) DEFAULT NULL, changed DATETIME DEFAULT NULL, PRIMARY KEY (event_id) ); DELIMITER // CREATE TRIGGER member_after_update AFTER UPDATE ON member FOR EACH ROW BEGIN INSERT INTO member_audit_trail SET action='update', id=OLD.id, old_name=OLD.name, name=NEW.name, changed=NOW(); END;// CREATE TRIGGER member_after_insert AFTER INSERT ON member FOR EACH ROW BEGIN INSERT INTO member_audit_trail

SET action='insert', id = NEW.id, name = NEW.name, changed=NOW(); END;// CREATE TRIGGER member_after_delete AFTER DELETE ON member FOR EACH ROW BEGIN INSERT INTO member_audit_trail SET action='delete', id=OLD.id, old_name=OLD.name, changed=NOW(); END;// DELIMITER ;

# The edits we made in Example 1 show up in the audit trail. > SELECT * FROM member_audit_trail;
+----------+------+----------+--------+----------+---------------------+ | event_id | id | old_name | action | name | | | | 1| 2| 3| 4| 1 | NULL 2 | NULL 3 | NULL | changed | +----------+------+----------+--------+----------+---------------------+ | insert | newton | 2006-06-12 04:16:05 | | insert | albert | 2006-06-12 04:16:05 | | insert | witten | 2006-06-12 04:16:05 |

2 | albert | update | einstein | 2006-06-12 04:16:36 |

+----------+------+----------+--------+----------+---------------------+

You might also like