Mysql 存储过程中使用多游标

Mysql 存储过程中使用多游标

复制代码
drop procedure IF EXISTS test_proc_1;
create procedure test_proc_1()
begin
    DECLARE done INT DEFAULT 0;
    DECLARE tid int(11) DEFAULT 0;
    DECLARE tname varchar(50) DEFAULT NULL;
    DECLARE tpass varchar(50) DEFAULT NULL;

    DECLARE cur_1 CURSOR FOR
        select name, password from netingcn_proc_test;

    DECLARE cur_2 CURSOR FOR
        select id, name from netingcn_proc_test;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    open cur_1;
    REPEAT
        FETCH cur_1 INTO tname, tpass;
        if not done then
            select tname, tpass;
        end if;
     UNTIL done END REPEAT;
    CLOSE cur_1;

    -- 注意这里,一定要重置done的值为 0
    set done = 0;

    open cur_2;
    REPEAT
        FETCH cur_2 INTO tid, tname;
        if not done then
            select tid, tname;
        end if;
     UNTIL done END REPEAT;
    CLOSE cur_2;
end


call test_proc_1();
复制代码

或者

复制代码
drop procedure IF EXISTS test_proc_2;
create procedure test_proc_2()
begin
    DECLARE done INT DEFAULT 0;
    DECLARE tname varchar(50) DEFAULT NULL;
    DECLARE tpass varchar(50) DEFAULT NULL;

    DECLARE cur_1 CURSOR FOR
        select name, password from netingcn_proc_test;

    DECLARE cur_2 CURSOR FOR
        select id, name from netingcn_proc_test;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    open cur_1;
    REPEAT
        FETCH cur_1 INTO tname, tpass;
        if not done then
            select tname, tpass;
        end if;
     UNTIL done END REPEAT;
    CLOSE cur_1;

    begin
        DECLARE done INT DEFAULT 0;
        DECLARE tid int(11) DEFAULT 0;
        DECLARE tname varchar(50) DEFAULT NULL;

        DECLARE cur_2 CURSOR FOR
            select id, name from netingcn_proc_test;

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

        open cur_2;
        REPEAT
            FETCH cur_2 INTO tid, tname;
            if not done then
                select tid, tname;
            end if;
         UNTIL done END REPEAT;
        CLOSE cur_2;
    end;
end


call test_proc_2();
复制代码

 

posted @   整合侠  阅读(3963)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2018-01-22 Python3.x:如何识别图片上的文字
点击右上角即可分享
微信分享提示