欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Mysql创建递归型的存储过程_MySQL

程序员文章站 2022-05-22 20:33:34
...
bitsCN.com

Mysql创建递归型的存储过程

第一步:SET max_sp_recursion_depth=12;

第二步:创建createChildDept过程

Sql代码

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

Sql代码

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)

bitsCN.com
相关标签: 存储