DELIMITER $$ CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT) BEGIN DECLARE vNeedToSplit BOOLEAN; DECLARE vNewTicketFk INT; DROP TEMPORARY TABLE IF EXISTS tmpSale; CREATE TEMPORARY TABLE tmpSale SELECT DISTINCT s.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk JOIN vn.packagingConfig pc WHERE t.id = vTicketFk AND ( s.quantity MOD IFNULL(iss.packing,1) != 0 OR IFNULL(iss.packing,1) = 1 OR i.`size` <= pc.previousPreparationMinimumSize ); SELECT COUNT(*) INTO vNeedToSplit FROM tmpSale; IF vNeedToSplit THEN CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); UPDATE vn.sale s JOIN vn.tmpSale ts ON ts.id = s.id SET s.ticketFk = vNewTicketFk; END IF; DROP TEMPORARY TABLE tmpSale; END$$ DELIMITER ;