DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_merge`(vTicketFk INT) BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vTicketFk AND it.isMergeable GROUP BY s.itemFk, s.price, s.discount; START TRANSACTION; UPDATE sale s JOIN tSalesToPreserve stp ON stp.id = s.id SET s.quantity = newQuantity WHERE s.ticketFk = vTicketFk; DELETE s.* FROM sale s LEFT JOIN tSalesToPreserve stp ON stp.id = s.id JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vTicketFk AND stp.id IS NULL AND it.isMergeable; COMMIT; DROP TEMPORARY TABLE tSalesToPreserve; END$$ DELIMITER ;