Create a recursive stored procedure in MySQL

Source: Internet
Author: User
Step 1: SETmax_sp_recursion_depth12; Step 2: Create the createChildDept process DELIMITER $ USE 'zhiku '$ DROPPROCEDUREIFEXIS

Step 1: SET max_sp_recursion_depth = 12; Step 2: Create the createChildDept process DELIMITER $ USE 'zhiku '$ DROP PROCEDURE IF EXIS

Step 1: SET max_sp_recursion_depth = 12;

Step 2: Create 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_orders ments 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;

Step 3: Create 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 region, zk_user_departments.user_id from zk_user_orders ments left join tmpLst on tmpLst. id = zk_user_departments.dept_id and region> rootId order by tmpLst. sno;
END $

DELIMITER;

Step 4: CALL showChildDept (128)

,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.