MYSQL游标嵌套循环 动态游标

本文展示了一个使用MySQL存储过程创建嵌套游标的示例,该示例从用户表中获取ID,并进一步检索每个用户的参数信息,最终将数据插入到另一个表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

drop procedure if exists `sp_nested_cursor`;
create procedure `sp_nested_cursor`()
begin
declare v_uid bigint(22);
    declare v_code varchar(100);
    declare v_value varchar(100);
    declare _done TINYINT(1) default 0;
declare cur_user cursor for select id from `tb_user`;
    declare continue handler for not found set _done = 1;
    
    open cur_user;
    loop_xxx:loop
    fetch cur_user into v_uid;
        if _done=1 then
        leave loop_xxx;
        end if;
        begin
        declare _inner tinyint(1) default 0;
        declare cur_param cursor for select code, value 
                                         from `tb_user_param` 
                                         where user_id=v_uid;
            declare continue handler for not found set _inner = 1; 
            open cur_param;
            loop_yyy:loop
            fetch cur_param into v_code, v_value;
                if _inner=1 then
                leave loop_yyy;
                end if;
                insert into tb_key_value values (v_uid, v_code, v_value);
            end loop;
            commit;
        end;
    end loop;
end;
call `sp_nested_cursor`();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值