Last active
September 30, 2015 18:38
-
-
Save memoryleak/1844595 to your computer and use it in GitHub Desktop.
create trigger syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE `_mydata` ( | |
`id` int(10) unsigned NOT NULL, | |
`version` int(10) unsigned NOT NULL, | |
`creation` datetime DEFAULT NULL, | |
`data` varchar(100) DEFAULT NULL, | |
`action` varchar(45) DEFAULT NULL, | |
PRIMARY KEY (`id`,`version`), | |
UNIQUE KEY `id_version` (`id`,`version`) | |
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TRIGGER <trigger_name> <BEFORE|AFTER> <INSERT|UPDATE|DELETE> | |
ON <table_name> FOR EACH ROW <trigger_body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER $$ | |
CREATE | |
TRIGGER `mydata_after_delete` | |
AFTER DELETE ON `mydata` | |
FOR EACH ROW | |
BEGIN | |
DECLARE nextversion int(10) unsigned; | |
SELECT (MAX(`version`) + 1) FROM `_mydata` WHERE id = OLD.id into nextversion ; | |
INSERT INTO `_mydata` VALUES(OLD.id, nextversion, NOW(), '', 'DELETE'); | |
END | |
$$ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER $$ | |
CREATE | |
TRIGGER `mydata_after_insert` | |
AFTER INSERT ON `mydata` | |
FOR EACH ROW | |
BEGIN | |
INSERT INTO `_mydata` VALUES(NEW.id, 1, NOW(), NEW.data, 'INSERT'); | |
END; | |
$$ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER $$ | |
CREATE | |
TRIGGER `mydata_after_update` | |
AFTER UPDATE ON `mydata` | |
FOR EACH ROW | |
BEGIN | |
DECLARE nextversion int(10) unsigned; | |
SELECT (MAX(`version`) + 1) FROM `_mydata` WHERE id = NEW.id into nextversion ; | |
INSERT INTO `_mydata` VALUES(NEW.id, nextversion, NOW(), NEW.data, 'UPDATE'); | |
END; | |
$$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment