DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionState_addByPallet`(vPalletFk INT, vStateCode VARCHAR(100))
BEGIN
/**
 * Inserta nuevos registros en la tabla vn.expeditionState
 * 
 * @param vPalletFk Identificador de vn.expedition
 * @param vStateCode Corresponde a vn.expeditionStateType.code
 */
	DECLARE hasExpeditions BOOL;

	DROP TEMPORARY TABLE IF EXISTS tExpeditionScan;
	CREATE TEMPORARY TABLE tExpeditionScan
		SELECT expeditionFk, est.id typeFk
			FROM vn.expeditionScan e
				JOIN vn.expeditionStateType est ON est.code = vStateCode
			WHERE e.palletFk = vPalletFk;

	SELECT COUNT(*) INTO hasExpeditions FROM tExpeditionScan;

	IF NOT hasExpeditions THEN
		DROP TEMPORARY TABLE tExpeditionScan;
		CALL util.throw('palletDoesNotExist'); 
	END IF;

	INSERT INTO vn.expeditionState(expeditionFk, typeFk)
		SELECT expeditionFk, typeFk
			FROM  tExpeditionScan;
	DROP TEMPORARY TABLE tExpeditionScan;
END$$
DELIMITER ;
