1.游标
什么是游标,以及游标使用的相关语法。
#声明游标,存储查询结果集
#准备:创建表结构
#开启游标
#获取游标中的记录
#插入数据到新表中
#关闭游标
create procedure p11(in uage int)
begin
declare uname varchar(100);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age <= uage;
drop table if exist tb_user_pro;
create table if not exist tb_user_pro(
id int primary key auto_increment,
name varchar(100),
profession varchar(100)
);
open u_cursor;
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro values (null, uname, upro);
end while;
close u_cursor;
end;
call p11(40);
解决游标中如果没有数据了,跳出循环的问题。
SQLSTATE为sql状态码。可以用not found来代替
declare exit handler for not found close u_cursor;
create procedure p11(in uage int)
begin
declare uname varchar(100);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age <= uage;
declare exit handler for SQLSTATE '02000' close u_cursor;
drop table if exist tb_user_pro;
create table if not exist tb_user_pro(
id int primary key auto_increment,
name varchar(100),
profession varchar(100)
);
open u_cursor;
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro values (null, uname, upro);
end while;
close u_cursor;
end;
call p11(40);