How to Use cursor nesting in MYSQL stored procedure development

Source: Internet
Author: User


In MYSQL stored procedure development, how to use cursors for nesting is inevitable in actual business logic development. For example: delimiter // drop PROCEDURE if exists good_nested_cursors1 // CREATE procedure good_nested_cursors1 () reads SQL DATABEGIN DECLARE l_grade_id INT; DECLARE l_class_id INT; DECLARE l_class_cnt INT DEFAULT 0; DECLARE l_done INT DEFAULT 0; www.2cto.com DECLARE grade_csr cursor FOR SELECT grade_id FROM org_grade; DECLARE class_csr cursor for select class_id FROM org_class WHERE grade_id = maid; declare continue handler for not found set l_done = 1; OPEN grade_csr; grade_loop: LOOP -- Loop through org_grade FETCH grade_csr into begin; select concat ('grade: ', l_grade_id); IF l_done = 1 then leave grade_loop; end if; OPEN class_csr; SET l_class_cnt = 0; class_loop: LOOP -- Loop through class in grade. FETCH class_csr INTO l_class_id; IF l_done = 1 then leave class_loop; end if; SET l_class_cnt = l_class_cnt + 1; select concat ('class: ', l_class_id); end loop; CLOSE class_csr; SET l_done = 0; www.2cto.com end loop grade_loop; CLOSE grade_csr; END; // delimiter; //////////////////////////////////////// /// // another example: create procedure curdemo () not deterministic contains SQL SECURITY DEFINER COMMENT ''BEGIN declare done1, done2 int default 0; declare name1, name2 varchar (20); declare id1, id2 int; www.2cto.com declare cur1 cursor for select id, name from test1; declare continue handler for not found set done1 = 1; open cur1; repeat fetch cur1 into id1, name1; if not done1 then insert into test3 (name) values (name1); begin declare cur2 cursor for select id, name from test2; declare continue handler for not found set done2 = 1; open cur2; repeat fetch cur2 into id2, name2; if not done2 then insert into test3 (name) values (name2); end if; www.2cto.com until done2 end repeat; close cur2; set done2 = 0; end if; until done1 end repeat; close cur1; commit; END; // by Cai lei

Related Article

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.