-- 游标
-- 根据传入的参数xb1,来查询用户表stue中,所有的用户性别等于xb1的用户姓名(name)和地址(d_z)
-- 并将用户的姓名和地址插入到所创建的一张新表,(id,name,d_z)中
-- 逻辑:
-- 声明游标,存储查询结果集
-- B.准备:创建表结构
-- C.开启游标
-- D.获取游标中的记录
-- E.插入数据到新表中
-- F.关闭游标
create procedure p11(in xb1 varchar(2)) -- 传入参数是字符型“男”
begin
declare uname varchar(50);
declare dizhi2 varchar(50);-- 先声明变量在声明游标
declare you_biao cursor for select name ,d_z from stue where xb= xb1 ; -- 游标变量名称为you_biao 指定类型是cursor for游标类型 将select name ,d_z from stue where xb= '男' 结果集合存储给游标变量
drop table if exists table_biao;-- 创建前如果表 yo_biao_b存在就删,为下期重新创建
create table if not exists table_biao --创表
(
id int primary key auto_increment,
name varchar(18),
dizhi varchar(30)
)comment '新表';
open you_biao;-- 打开游标
while true do -- 用循环的方式获取游标中的字段信息
fetch you_biao into uname,dizhi2; -- 将游标集合中的字段用fetch..into 方式赋值给自定义变量
insert into table_biao values (null,uname,dizhi2); -- 因为id是 auto_increment自增的,所以它的id字段可写null
end while;
close you_biao;-- 关闭游标
end;
call p11('男');
仍然报错是因为无法退出循环(即使游标中已经无内容也不能退出循环)
create procedure p11(in xb1 varchar(2)) -- 传入参数是字符型“男”
begin
declare uname varchar(50);
declare dizhi2 varchar(50);-- 先声明变量在声明游标
declare you_biao cursor for select name ,d_z from stue where xb= xb1 ; -- 游标变量名称为you_biao 指定类型是cursor for游标类型 将select name ,d_z from stue where xb= '男' 结果集合存储给游标变量
declare exit handler for SQLSTATE '02000' close you_biao;-- 声明一个条件处理函数,当符号SQL这个状态码(报错时的状态码)时就触发了exit退出操作,且退出时将游标关掉
-- SQLSTATE '02000'可以换成not found
drop table if exists table_biao;-- 创建前如果表 yo_biao_b存在就删,为下期重新创建
create table if not exists table_biao
(
id int primary key auto_increment,
name varchar(18),
dizhi varchar(30)
)comment '新表';
open you_biao;-- 打开游标
while true do -- 用循环的方式获取游标中的字段信息
fetch you_biao into uname,dizhi2; -- 将游标集合中的字段用fetch..into 方式赋值给自定义变量
insert into table_biao values (null,uname,dizhi2); -- 因为id是 auto_increment自增的,所以它的id字段可写null
end while;-- 循环报错就进入条件处理函数
close you_biao;-- 关闭游标
end;
call p11('男');