MySQL-存储过程--游标
存储过程
游标
什么是游标
一个游标是一个SQL语句执行时系统内存创建的一个临时工作区域。一个游标包含一个查询语句的信息和它操作的数据行的信息。
mysql游标的特点
- 只读: 无法通过游标更新基础表中的数据
- 不可滚动: 只能根据select中确定的顺序来获取行数据,不能跳行
- 敏感:敏感游标使用实际的数据,不敏感游标使用实际数据的副本,敏感游标速度快,但如果更新数据则会影响实际数据,mysql游标是敏感的同时是只读的
基础语法
A. 声明游标
DECLARE 游标名称 CURSOR 1 FOR 查询语句 ;
B. 打开游标
OPEN 游标名称 ;
C. 获取游标记录
FETCH 游标名称 INTO 变量 [, 变量 ] ;
D. 关闭游标
CLOSE 游标名称 ;
游标开发示例
准备工作:
# 班级定义表
create table t_class (
cid int not null auto_increment,
cname varchar(40),
primary key (cid)
) engine=innodb charset=utf8 collate=utf8_general_ci;
# 学生表
create table t_student(
sid int not null auto_increment,
sname varchar(40),
score int,
class int,
primary key (sid)
)engine=innodb charset=utf8 collate=utf8_general_ci;
# 学生等级
create table t_grade(
gid int not null auto_increment,
cid int not null,
A int not null default 0,
B int not null default 0,
C int not null default 0,
D int not null default 0,
primary key (gid)
) engine=innodb charset=utf8 collate=utf8_general_ci;
# 班级定义表
create table t_class ( cid int not null auto_increment,cname varchar(40),primary key (cid)
) engine=innodb charset=utf8 collate=utf8_general_ci;
# 学生表
create table t_student ( sid int not null auto_increment,sname varchar(40),score int,class int,primary key (sid)
) engine=innodb charset=utf8 collate=utf8_general_ci;
# 学生等级
create table t_grade ( gid int not null auto_increment,cid int not null,A int not null default 0,B int not null default 0,C int not null default 0,D int not null default 0,primary key (gid)
) engine=innodb charset=utf8 collate=utf8_general_ci;
功能描述: 统计每个班的学生数据,并进行成绩分类:
- 大于等于90 为A
- 大于等于75分小于90分为B
- 大于等于60分小于75分为C
- 小于60分为D
将统计的数据存放在下面的表格t_grade中,下面为测试数据
insert into `t_student`(`sid`,`sname`,`score`,`class`) values (1,'小明',90,1),(2,'小李子',95,1),(3,'张三丰',60,1),(4,'王紫',50,1),(5,'王敏',75,1),(6,'赵晓峰',90,2),(7,'刘小锋',80,2),(8,'孙涛',75,2),(9,'朱晓',40,2),(10,'李思敏',78,2),(11,'王晓飞',95,3),(12,'吴蒙',90,3),(13,'夏非',80,3),(14,'郑宝',92,3);
存储过程如下:
drop procedure if exists pro_stat_score;
delimiter $
create procedure pro_stat_score()
begin
declare a int default 0;
declare b int default 0;
declare c int default 0;
declare d int default 0;
declare done boolean default true;
declare cls_cid int default 0;
declare cls_cur cursor for select cid from t_class;
declare continue handler for not found set done=false;
open cls_cur;
while done do
fetch cls_cur into cls_cid;
select COUNT(*) into a from t_student where class=cls_cid and score >= 90;
select COUNT(*) into b from t_student where class=cls_cid and score >=75 and score <90;
select COUNT(*) into c from t_student where class=cls_cid and score >=60 and score <75;
select COUNT(*) into d from t_student where class=cls_cid and score <60;
insert into t_grade(cid,A,B,C,D)values(cls_cid,a,b,c,d);
end while;
close cls_cur;
end $
delimiter ;