Rumah >pangkalan data >tutorial mysql >Mysql创建递归型的存储过程_MySQL

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBasal
2016-06-01 13:37:241329semak imbas

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
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn