DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`rate_getPrices`(
	vDated DATE,
	vWarehouseFk INT
)
BEGIN
/**
 * Prepara una tabla con las tarifas aplicables
 * en funcion de la fecha y el almacén.
 *
 * @param vDated Fecha para la cual calcula la tarifa
 * @param vWarehouseFk Warehouse para el cual calcula la tarifa
 * @return tmp.rate (rate0, rate1, rate2, rate3)
 */
	CREATE OR REPLACE TEMPORARY TABLE tmp.rate
		ENGINE = MEMORY
		SELECT rate0,
				rate1,
				rate2,
				rate3
			FROM(
				(SELECT 1 `order`,
						rate0,
						rate1,
						rate2,
						rate3
					FROM rate
					WHERE dated <= vDated
						AND warehouseFk = vWarehouseFk
					ORDER BY dated DESC
					LIMIT 1
				)
				UNION
				(SELECT 2,
						rate0,
						rate1,
						rate2,
						rate3
					FROM rateConfig
				)
				ORDER BY `order` ASC
				LIMIT 1
			)sub;
END$$
DELIMITER ;
