Throw an error in a MySQL trigger

后端 未结 7 1017
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:59

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条回答
  •  北海茫月
    2020-11-22 12:58

    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 ;
    

提交回复
热议问题