本篇内容介绍了“MYSQL存储过程开发中怎么使用游标嵌套”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
在实际业务逻辑开发中,难免用到游标嵌套,举例如下:
delimiter // drop procedure if exists good_nested_cursors1 // CREATE PROCEDURE good_nested_cursors1( ) READS SQL DATA BEGIN 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=l_grade_id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1; OPEN grade_csr; grade_loop: LOOP -- Loop through org_grade FETCH grade_csr into l_grade_id; select concat('年级:', 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(' 班级:', l_class_id); END LOOP; CLOSE class_csr; SET l_done=0; www.2cto.com END LOOP grade_loop; CLOSE grade_csr; END; // delimiter ; /////////////////////////////////////////////////////// //另一个例子: CREATE PROCEDURE curdemo() NOT DETERMINISTIC CONTAINS SQL 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; end if; until done1 end repeat; close cur1; commit; END; ///
“MYSQL存储过程开发中怎么使用游标嵌套”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。