Created
August 20, 2014 03:25
-
-
Save cunneen/01c9170dfdd863286080 to your computer and use it in GitHub Desktop.
Mimicking Check Constraints in MySQL
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
-- Modified from: http://stackoverflow.com/a/14248038/956779 | |
-- Add a BEFORE INSERT constraint that only allows values between 1 and 5 | |
DELIMITER $$ | |
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON cheese_shop.items | |
FOR EACH ROW | |
BEGIN | |
IF (NEW.ratings > 5 OR NEW.ratings < 1) THEN | |
SIGNAL SQLSTATE '12345' | |
SET MESSAGE_TEXT = 'check constraint on items.ratings failed'; | |
END IF; | |
END$$ | |
DELIMITER ; | |
-- Add a BEFORE UPDATE constraint that only allows values between 1 and 5 | |
DELIMITER $$ | |
CREATE TRIGGER `test_before_update` BEFORE UPDATE ON cheese_shop.items | |
FOR EACH ROW | |
BEGIN | |
IF (NEW.ratings > 5 OR NEW.ratings < 1) THEN | |
SIGNAL SQLSTATE '12345' | |
SET MESSAGE_TEXT = 'check constraint on items.ratings failed'; | |
END IF; | |
END$$ | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment