Throw an error preventing a table update in a MySQL trigger

Viewed 98408

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?

7 Answers

Here is one hack that may work. It isn't clean, but it looks like it might work:

Essentially, you just try to update a column that doesn't exist.

DELIMITER @@
DROP TRIGGER IF EXISTS trigger_name @@
CREATE TRIGGER trigger_name 
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN

  --the condition of error is: 
  --if NEW update value of the attribute age = 1 and OLD value was 0
  --key word OLD and NEW let you distinguish between the old and new value of an attribute

   IF (NEW.state = 1 AND OLD.state = 0) THEN
       signal sqlstate '-20000' set message_text = 'hey it's an error!';     
   END IF;

END @@ 
DELIMITER ;
Related