Created
February 23, 2015 15:30
-
-
Save kstefan/d106ac428c7dcabae6e6 to your computer and use it in GitHub Desktop.
PL/SQL recalculate tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # SET @@session.max_sp_recursion_depth = 255; | |
| # CALL recalculateTree(NULL, 0, 0, @index); | |
| CREATE PROCEDURE recalculateTree(IN parent INT, IN i INT, IN depth INT, OUT ri INT) | |
| BEGIN | |
| DECLARE done INT DEFAULT FALSE; | |
| DECLARE n_id INT; | |
| DECLARE n_parent_id INT; | |
| DECLARE n_lft INT; | |
| DECLARE n_rgt INT; | |
| DECLARE tmp_i INT; | |
| DECLARE cur CURSOR FOR | |
| SELECT id, parent_id, lft, rgt | |
| FROM category | |
| WHERE | |
| COALESCE(parent_id, -1) = COALESCE(parent, -1) | |
| ; | |
| DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; | |
| OPEN cur; | |
| read_loop: LOOP | |
| FETCH cur INTO n_id, n_parent_id, n_lft, n_rgt; | |
| IF done THEN | |
| LEAVE read_loop; | |
| END IF; | |
| IF n_parent_id IS NULL THEN | |
| SET depth = 0; | |
| END if; | |
| SET i = i + 1; | |
| SET tmp_i = i; | |
| CALL recalculateTree(n_id, i, depth + 1, @ii); | |
| SET i = @ii + 1; | |
| UPDATE category set lft = tmp_i, rgt = i, lvl = depth where id = n_id; | |
| END LOOP; | |
| CLOSE cur; | |
| SET ri = i; | |
| END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment