DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`expeditionState_add`(vParam INT, vStateCode VARCHAR(100))
BEGIN
	
	/**
	 * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro
	 * 
	 * @param vParam Identificador de vn.expedition o de vn.route
	 * @param vStateCode Corresponde a vn.expeditionStateType.code
	 */
	
	IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN
	
		INSERT INTO vn.expeditionState(expeditionFk, typeFk)
			SELECT e.id, est.id
				FROM vn.expedition e
					JOIN vn.ticket t ON t.id = e.ticketFk
					JOIN vn.expeditionStateType est ON est.code = vStateCode
				WHERE t.routeFk = vParam;
		
	ELSE
	
		INSERT INTO vn.expeditionState(expeditionFk, typeFk)
			SELECT vParam, est.id
				FROM vn.expeditionStateType est
				WHERE est.code = vStateCode;
			
	END IF;
			
END$$
DELIMITER ;
