DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_doReserve`()
proc: BEGIN
/**
 * Genera reservas de la tabla vn.itemShelvingSaleReserve
 */
	DECLARE vDone BOOL;
	DECLARE vSaleFk INT;
	DECLARE vSectorFk INT;

	DECLARE vSales CURSOR FOR
		SELECT DISTINCT saleFk FROM tSale;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('vn.itemShelvingSale_doReserve');
		ROLLBACK;
		RESIGNAL;
	END;

	IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN
		LEAVE proc;
	END IF;

	CREATE OR REPLACE TEMPORARY TABLE tSale
		ENGINE = MEMORY
		SELECT id, saleFk, sectorFk FROM itemShelvingSaleReserve;

	OPEN vSales;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vSales INTO vSaleFk, vSectorFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL itemShelvingSale_addBySale (vSaleFk, vSectorFk);
	END LOOP;

	CLOSE vSales;

	DELETE iss FROM itemShelvingSaleReserve iss 
		JOIN tSale s ON s.id = iss.id AND s.sectorFk = iss.sectorFk;

	DROP TEMPORARY TABLE tSale;

	DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); 
END$$
DELIMITER ;