Here is the code:
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();
I was expecting that the function would put the deleted animal entry into the deleted animals table, but it doesn’t work.
2
Answers
MySQL doesn’t have
RETURN TRIGGER
like PostGres does. Use an ordinary stored procedure, and pass the animal ID as a parameter.The
SELECT
subquery that gets the animal name can’t work, since the trigger runs after that row has been deleted. So passOLD.animal_name
as a parameter.You are using a stored procedure syntax instead of a trigger syntax:
Try this: