MySQL游标

游标(cursor)是用来存储查询结果集的数据类型,在存储过程和函数中可以使用游标对结果集进行循环处理。

-- 游标
-- 根据传入的参数uage,来查询用户表tb_user中,所有用户年龄小于uage的用户姓名(name)和专业(profession)
-- 并将用户的姓名和专业插入到所创建的一张新表(id,name,profession)


-- 逻辑:
-- A、声明游标,来存储查询结果集
-- B、准备:创建表结构
-- C、开启游标
-- D、获取游标中的记录
-- E、插入数据到新表
-- F、关闭游标


create procedure p11(in uage int )
begin
    declare uname varchar(100);
    declare upro varchar(100);
    -- 游标声明 declare 游标名称 cursor for 查询语句;
    declare u_cursor cursor for select name,profession from tb_user where age <=uage;
    
    -- 声明条件处理程序:游标数据集获取完毕,将关闭游标并退出
    -- 以02开头的sqlstate是 not found
    declare exit handler for sqlstate '02000' close u_cursor;


    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro(
        id int primary key auto_increment,
        name varchar(100),
        profession varchar(100)
    );

    -- 打开游标 open 游标名称;
    open u_cursor;
    while true do
        -- 获取游标记录 fetch 游标名称 into 变量;
        fetch u_cursor into uname,upro;
        insert into tb_user_pro values (null,uname,upro);
    end while;
    close u_cursor;-- 关闭游标


end;

call p11(40);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值