How to abort INSERT operation in MySql trigger?

I came across this and although the solution works I later came across what feels to me like a better solution. I suspect this wasn’t an option when this question was originally answered.

CREATE TRIGGER `TestTable_SomeTrigger`
BEFORE UPDATE ON `test_table`
FOR EACH ROW
BEGIN
    DECLARE msg VARCHAR(255);
    IF (SomeTestToFail = "FAIL!") THEN
        set msg = "DIE: You broke the rules... I will now Smite you, hold still...";
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
    END IF;

    -- Do any other code here you may want to occur if it's all OK or leave blank it will be
    --  skipped if the above if is true
END$$

This will now return a nice (or evil!) error message that you can trap.
For more info on this see: http://dev.mysql.com/doc/refman/5.5/en/signal.html

I hope this helps someone else!

Leave a Comment