代码如下:
CREATE FUNCTION animal_delete_func()
RETURNS TRIGGER
BEGIN
-- Delete the feeding schedule entries for the animal
DELETE FROM feeding_schedule WHERE animal_id = OLD.animal_id;
-- Delete the food entries for the animal
DELETE FROM food WHERE animal_id = OLD.animal_id;
-- INSERT into deleted_animals table
INSERT INTO deleted_animals (animal_id, animal_name, date_deleted)
VALUES (OLD.animal_id, (SELECT animal_name FROM animals WHERE animal_id = OLD.animal_id), NOW());
RETURN OLD
END$$
-- Set delimiter back to ;
DELIMITER ;
-- trigger that calls animal_delete_func() everytime an animal is deleted from the animals table
CREATE TRIGGER animal_delete_trigger
AFTER DELETE ON animals
FOR EACH ROW
CALL animal_delete_func();
我期望该函数将删除的动物条目放入删除的动物表中,但它不起作用。
2条答案
按热度按时间gab6jxml1#
MySQL不像PostGres那样有
RETURN TRIGGER
。使用一个普通的存储过程,并将动物ID作为参数传递。获取动物名称的
SELECT
子查询无法工作,因为触发器在该行被删除 * 之后运行。因此将OLD.animal_name
作为参数传递。bfnvny8b2#
您正在使用存储过程语法而不是触发器语法:试试这个: