DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketTracking_afterDelete` AFTER DELETE ON `ticketTracking` FOR EACH ROW BEGIN DECLARE vTicketFk INT; DECLARE vTicketTrackingFk INT; DECLARE vStateName VARCHAR(15); DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' BEGIN DELETE FROM vn.ticketLastState WHERE ticketFk = OLD.ticketFk; END; INSERT INTO ticketLog SET `action` = 'delete', `changedModel` = 'TicketTracking', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); CALL util.debugAdd('deletedState', CONCAT('interFk: ', OLD.id, ' ticketFk: ', OLD.ticketFk, ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` INTO vTicketFk, vTicketTrackingFk, vStateName FROM ticketTracking i JOIN state s ON i.stateFk = s.id WHERE ticketFk = OLD.ticketFk ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN REPLACE INTO ticketLastState(ticketFk, ticketTrackingFk,name) VALUES(vTicketFk, vTicketTrackingFk, vStateName); END IF; END$$ DELIMITER ;