DELIMITER ;;
CREATE DEFINER=`webdev`@`localhost` PROCEDURE `update_tree`(IN _pageID INT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE _id INT;
DECLARE curs CURSOR FOR SELECT DISTINCT(descendant) FROM PageClosure WHERE ancestor = _pageID OR descendant = _pageID;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs;
REPEAT
FETCH curs INTO _id;
IF ! done THEN
UPDATE PageClosure t
JOIN (SELECT c.descendant, COUNT(c.ancestor) -1 AS `depth` FROM PageClosure c GROUP BY c.descendant ) AS d ON (d.descendant = t.descendant)
SET t.`depth` = d.`depth`
WHERE t.descendant = _id;
END IF;
UNTIL done END REPEAT;
CLOSE curs;
END;;
DELIMITER ;