>데이터 베이스 >MySQL 튜토리얼 >MySQL创建递归型的存储过程

MySQL创建递归型的存储过程

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB원래의
2016-06-07 17:24:571190검색

第一步: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)

linux

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.