DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entryDelivered`(vDated DATE, vEntryFk INT) BEGIN DECLARE vTravelFk INT; SELECT travelFk INTO vTravelFk FROM vn.entry WHERE id = vEntryFk; IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; ELSE INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; SELECT LAST_INSERT_ID() INTO vTravelFk; UPDATE vn.entry SET travelFk = vTravelFk WHERE id = vEntryFk; END IF; END$$ DELIMITER ;