使用TRIGGER取消删除

时间:2011-11-08 20:55:23

标签: mysql triggers abort

我想取消DELETE的TRIGGER。这个想法是BEFORE DELETE,设置列hide = "Y"然后取消TRIGGER事件而不是真的删除该行。

有可能吗?

1 个答案:

答案 0 :(得分:5)

您可以取消删除,但无法更改DELETE触发器中的值。

DELIMITER $$

CREATE TRIGGER bd_t1_each BEFORE DELETE ON t1 FOR EACH ROW
BEGIN
  //This will not work, because the `NEW` virtual table does not exist in a delete trigger.
  SET NEW.hide = 'Y';
  //Raising an error will work.
  SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'DELETE canceled'; 
END $$

DELIMITER ;

相反,您应该创建一个存储过程来隐藏您的行:

DELIMITER $$

CREATE PROCEDURE delete_t1_row (pID INTEGER)
BEGIN
  UPDATE t1 SET hide = 'Y' WHERE id = pID;
END $$

DELIMITER ;