DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_doRecalc`()
proc: BEGIN
/**
 * Recalculates modified ticket.
 */
	DECLARE vDone BOOL;
	DECLARE vTicketFk INT;

	DECLARE cCur CURSOR FOR
		SELECT DISTINCT ticketFk FROM tTicket;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

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

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

	DROP TEMPORARY TABLE IF EXISTS tTicket;
	CREATE TEMPORARY TABLE tTicket
		ENGINE = MEMORY
		SELECT id, ticketFk FROM ticketRecalc;

	OPEN cCur;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cCur INTO vTicketFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL ticket_recalc(vTicketFk, NULL);
	END LOOP;

	CLOSE cCur;

	DELETE tr FROM ticketRecalc tr JOIN tTicket t ON tr.id = t.id;

	DROP TEMPORARY TABLE tTicket;

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