Mysql存储过程创建 循环中游标的简单使用

-- 如果存在就删除
drop procedure if exists pro_f;

-- 创建存储过程
create procedure pro_f()
begin
    -- 定义变量
    declare p_id INT default 0;
    declare p_name varchar(50) default '';
    -- 定义游标遍历时的标记
    declare flag INT DEFAULT 0;
    -- 定义数据存储集合
    declare product_list cursor for select id,name_test from test ;
    -- 定义游标遍历结束标识
    declare continue handler for not found SET flag=1;    
    -- 创建临时表-保存记录-只是为了结果更直观
    CREATE TEMPORARY TABLE info_temp (
            id int(11) NOT NULL AUTO_INCREMENT,
            msg varchar(255) NOT NULL,
            PRIMARY KEY (Id)
    );

    -- 打开游标
    open product_list;
    -- 将游标中的第一行值赋值给已经定义好的变量-并移动行
    fetch product_list into p_id,p_name;
    -- 循环
    repeat 
        if p_id > 1 then 
            insert into info_temp values(p_id,p_name);
        end if;
    -- 获得下一行数据
        FETCH product_list INTO p_id,p_name;
        -- 终止循环标识
        until flag = 1 end repeat;
    -- 关闭游标
    close product_list;

    -- 查询数据
    SELECT *  FROM info_temp;
    -- 删除临时表
    drop table info_temp;
end

-- call pro_f(); -- 另起一个窗口执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值