Skip to content

Instantly share code, notes, and snippets.

@vaibhavi3t
Created July 13, 2016 12:56
Show Gist options
  • Save vaibhavi3t/4a099f53ec71707a986cb695ab647307 to your computer and use it in GitHub Desktop.
Save vaibhavi3t/4a099f53ec71707a986cb695ab647307 to your computer and use it in GitHub Desktop.
Mysql trigger to log the after update and after insert in a table. First trigger is to record the status of listing after update and second one to record the after insert status.
LISTING STATUS CHANGE TRACK
1. Table listing_status_track to log the listing status change.
create table listing_status_track (
listing_id int(10) unsigned,
status_from enum('incomplete','inactive','active','expired','truebiled','booked','soldByOthers'),
status_to enum('incomplete','inactive','active','expired','truebiled','booked','soldByOthers'),
changed_at TIMESTAMP default current_timestamp,
FOREIGN KEY (listing_id) REFERENCES listings(id)
);
2. Trigger to record in listing_status_track table
a. listing_status_change_after_update
DELIMITER $$
CREATE
TRIGGER listing_status_change_after_update AFTER UPDATE
ON listings
FOR EACH ROW BEGIN
SET @oldStatus = OLD.status;
SET @newStatus = NEW.status;
INSERT INTO listing_status_track (listing_id, status_from, status_to) VALUES (NEW.id, @oldStatus, @newStatus);
END$$
DELIMITER ;
b.Listing_status_change_after_insert
DELIMITER $$
CREATE
TRIGGER listing_status_change_after_insert AFTER INSERT
ON listings
FOR EACH ROW BEGIN
SET @status = NEW.status;
INSERT INTO listing_status_track (listing_id, status_to) VALUES (NEW.id, @status);
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment