DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`item_buy`(IN v_wh TINYINT, IN v_date DATETIME)
BEGIN
	DECLARE date_inv DATE;
	ALTER TABLE item
		ADD buy_id INT UNSIGNED;
	
	IF v_date < (SELECT vn.getInventoryDate()) THEN
		SELECT MIN(landing) INTO date_inv FROM travel t INNER JOIN Entradas e ON e.travel_id = t.id 
			WHERE warehouse_id_out = 13 AND landing <= v_date;
	ELSE
		SET date_inv = vn.getInventoryDate();
	END IF;
	UPDATE item i INNER JOIN (
		SELECT * FROM (
			SELECT c.Id_Article item_id, c.Id_Compra id
				FROM Compres c INNER JOIN Entradas e USING(Id_Entrada)
      				INNER JOIN travel t ON t.id = e.travel_id
					WHERE t.landing BETWEEN date_inv AND v_date
					AND c.Novincular = FALSE
					AND c.Tarifa2 >= 0
					ORDER BY  v_wh = t.warehouse_id DESC, t.landing DESC
					LIMIT 10000000000000000000
		) t
		GROUP BY item_id
	) t
	ON i.id = t.item_id
		SET i.buy_id = t.id;

	CREATE INDEX buy USING HASH ON item (buy_id);
END$$
DELIMITER ;
