MySQL创建递归型的存储过程
第一步:SET max_sp_recursion_depth=12; 第二步:创建createChildDept过程 DELIMITER $$ USE `zhiku`$$ DROP PROCEDURE IF EXIS
第一步:SET max_sp_recursion_depth=12;
第二步:创建createChildDept过程
DELIMITER $$
USE `zhiku`$$
DROP PROCEDURE IF EXISTS `createChildDept`$$
CREATE DEFINER=`root`@`%` PROCEDURE `createChildDept`(IN rootId INT,IN nDepth INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE b INT;
DECLARE cur1 CURSOR FOR SELECT id FROM zk_departments WHERE parent_id=rootId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
INSERT INTO tmpLst VALUES (NULL,rootId,nDepth);
OPEN cur1;
FETCH cur1 INTO b;
WHILE done=0 DO
CALL createChildDept(b,nDepth+1);
FETCH cur1 INTO b;
END WHILE;
CLOSE cur1;
END$$
DELIMITER ;
第三步:创建showChildDept
DELIMITER $$
USE `zhiku`$$
DROP PROCEDURE IF EXISTS `showChildDept`$$
CREATE DEFINER=`root`@`%` PROCEDURE `showChildDept`(IN rootId INT)
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS tmpLst
(sno INT PRIMARY KEY AUTO_INCREMENT,id INT,depth INT);
DELETE FROM tmpLst;
CALL createChildDept(rootId,0);
SELECT zk_departments.id,zk_departments.name FROM tmpLst,zk_departments WHERE tmpLst.id=zk_departments.id AND zk_departments.id>rootId ORDER BY tmpLst.sno;
#select zk_user_departments.dept_id,zk_user_departments.user_id from zk_user_departments left join tmpLst on tmpLst.id=zk_user_departments.dept_id and zk_user_departments.dept_id>rootId order by tmpLst.sno;
END$$
DELIMITER ;
第四步:CALL showChildDept(128)
,上一篇: 《提问的智慧,智慧的提问》不得不提醒一下,该如何处理
下一篇: 关系模型(三)