DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_multipleBuy`( vDate DATETIME, vWarehouseFk INT ) BEGIN /** * Updates the tmp.itemInventory table, adding the buy id. * * @param tmp.itemInventory(buy_id) * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; CALL buy_getUltimate (NULL, vWarehouseFk, vDate); CREATE OR REPLACE TEMPORARY TABLE tmp (KEY (itemFk)) ENGINE = MEMORY SELECT * FROM ( SELECT itemFk, buyFk FROM tmp.buyUltimate ORDER BY (vWarehouseFk = warehouseFk) DESC, landing DESC LIMIT 10000000000000000000 ) t GROUP BY itemFk; UPDATE tmp.itemInventory ai JOIN tmp t ON ai.id = t.itemFk SET ai.buy_id = t.buyFk; DROP TEMPORARY TABLE tmp, tmp.buyUltimate; END$$ DELIMITER ;