USE `vn`;
DROP procedure IF EXISTS `department_doCalc`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`()
proc: BEGIN
/**
 * Recalculates the department tree.
 */
    DECLARE vIsChanged BOOL;

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

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

	SELECT isChanged INTO vIsChanged
		FROM department_recalc;
        
	IF vIsChanged THEN
		UPDATE department_recalc SET isChanged = FALSE;
        CALL vn.department_calcTree;
	END IF;

	DO RELEASE_LOCK('vn.department_doCalc');
END$$

DELIMITER ;

