DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`worker_updateChangedBusiness`()
BEGIN
/**
 * Actualiza el contrato actual de todos los trabajadores cuyo contracto ha
 * empezado/vencido.
 */
	DECLARE vBusinessUpdated DATE;
	DECLARE vCurdate DATE DEFAULT util.VN_CURDATE();
	DECLARE vWorkerFk INT;
	DECLARE vDone BOOL;

	DECLARE vCursor CURSOR FOR
		SELECT DISTINCT b.workerFk 
			FROM business b 
				WHERE b.started > vBusinessUpdated AND b.started <= vCurdate
					OR b.ended >= vBusinessUpdated AND b.ended < vCurdate;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	SELECT businessUpdated INTO vBusinessUpdated
		FROM workerConfig;

	OPEN vCursor;

	l: LOOP
		SET vDone = FALSE;

		FETCH vCursor INTO vWorkerFk;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL worker_updateBusiness(vWorkerFk);
	END LOOP;

	UPDATE workerConfig SET businessUpdated = vCurdate;
END$$
DELIMITER ;
