欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > MySql---进阶篇(十一)----游标,条件处理程序,存储函数

MySql---进阶篇(十一)----游标,条件处理程序,存储函数

2025/6/8 16:54:45 来源:https://blog.csdn.net/ABCabc0286/article/details/144942493  浏览:    关键词:MySql---进阶篇(十一)----游标,条件处理程序,存储函数

11.1:游标介绍:

游标( CURSOR )是用来存储查询结果集的数据类型 , 在存储过程和函数中可以使用游标对结果集进行循环的处理。游标的使用包括游标的声明、OPEN FETCH CLOSE ,其语法分别如下。
A. 声明游标
DECLARE 游标名称 CURSOR FOR 查询语句 ;
B. 打开游标
OPEN 游标名称 ;

C. 获取游标记录
FETCH 游标名称 INTO 变量 [, 变量 ] ;

D. 关闭游标
close  游标名称;
2). 案例
根据传入的参数 uage ,来查询用户表 tb_user 中,所有的用户年龄小于等于 uage 的用户姓名
name )和专业( profession ),并将用户的姓名和专业插入到所创建的一张新表
(id,name,profession) 中。
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 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 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(30);
上述的存储过程,最终我们在调用的过程中,会报错,之所以报错是因为上面的 while 循环中,并没有退出条件。当游标的数据集获取完毕之后,再次获取数据,就会报错,从而终止了程序的执行。
接下来,我们就需要来完成这个存储过程,并且解决这个问题。要想解决这个问题,就需要通过MySQL 中提供的 条件处理程序 Handler 来解决。

11.2,条件处理程序:

1). 介绍
条件处理程序( Handler )可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。具体语法为:
DECLARE handler_action HANDLER FOR condition_value [, condition_value]
... statement ;
handler_action 的取值:
CONTINUE: 继续执行当前程序
EXIT: 终止执行当前程序
condition_value 的取值:
SQLSTATE sqlstate_value: 状态码,如 02000
SQLWARNING: 所有以01开头的SQLSTATE代码的简写
NOT FOUND: 所有以02开头的SQLSTATE代码的简写
SQLEXCEPTION: 所有没有被SQLWARNING 或 NOT FOUND捕获的SQLSTATE代码的简写
2). 案例
我们继续来完成在上一小节提出的这个需求,并解决其中的问题。
根据传入的参数 uage ,来查询用户表 tb_user 中,所有的用户年龄小于等于 uage 的用户姓名
name )和专业( profession ),并将用户的姓名和专业插入到所创建的一张新表
(id,name,profession) 中。
A. 通过 SQLSTATE 指定具体的状态码
create procedure p11(in uage int)
begindeclare uname varchar(100);declare upro varchar(100);declare u_cursor cursor for select nam,profession form tb_user where age<=uage;declare exit handler for SQLSTATE '02000' close u_cursor;drop table if exists tb_user_pro;create table tb_user_pro (id int primary key auto_increment,name varchar(100),rofession 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(30);
B. 通过 SQLSTATE 的代码简写方式 NOT FOUND
02 开头的状态码,代码简写为 NOT FOUND
create procedure p12(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;
-- 声明条件处理程序 : 当SQL语句执行抛出的状态码为02开头时,将关闭游标u_cursor,并退出
declare exit handler for not found 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 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 p12(30);

11.3,存储函数:

存储函数是有返回值的存储过程,存储函数的参数只能是 IN 类型的。具体语法如下:
CREATE FUNCTION 存储函数名称 ([ 参数列表 ])
RETURNS type [characteristic ...]
BEGIN
-- SQL语句
RETURN ...;
END ;
characteristic 说明:
DETERMINISTIC :相同的输入参数总是产生相同的结果。
NO SQL :不包含 SQL 语句。。
READS SQL DATA :包含读取数据的语句,但不包含写入数据的语句。
2). 案例
计算从 1 累加到 n 的值, n 为传入的参数值。
create function fun1(n int)
returns int deterministic
begin
declare total int default 0;
while n>0 do
set total := total + n;
set n := n - 1;
end while;
return total;
end;
select fun1(50);
mysql8.0 版本中 binlog 默认是开启的,一旦开启了, mysql 就要求在定义存储过程时,需要指定
characteristic 特性,否则就会报错误。

11.4:触发器:

触发器是与表有关的数据库对象,指在 insert/update/delete 之前 (BEFORE) 或之后 (AFTER) ,触
发并执行触发器中定义的 SQL 语句集合。触发器的这种特性可以协助应用在数据库端确保数据的完整性 , 日志记录 , 数据校验等操作 。使用别名OLD NEW 来引用触发器中发生变化的记录内容,这与其他的数据库是相似的。现在触发器还只支持行级触发,不支持语句级触发。

  语法
1). 创建
CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON tbl_name FOR EACH ROW -- 行级触发器
BEGIN
trigger_stmt ;
END;
2). 查看
SHOW TRIGGERS ;
3). 删除
DROP TRIGGER [schema_name.]trigger_name ; -- 如果没有指定 schema_name,默认为当前数
据库 。
案例
通过触发器记录 tb_user 表的数据变更日志,将变更日志插入到日志表 user_logs , 包含增加 ,
修改 , 删除 ;
表结构准备 :
-- 准备工作 : 日志表 user_logs
create table user_logs(
id int(11) not null auto_increment,
operation varchar(20) not null comment '操作类型, insert/update/delete',
operate_time datetime not null comment '操作时间',
operate_id int(11) not null comment '操作的ID',
operate_params varchar(500) comment '操作参数',
primary key(`id`)
)engine=innodb default charset=utf8;
A. 插入数据触发器
create trigger tb_user_insert_triggerafter insert on tb_user for each row
begininsert into user_logs(id, operation, operate_time, operate_id, operate_params)
VALUES
(null, 'insert', now(), new.id, concat('插入的数据内容为:
id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ',
profession=', NEW.profession));
end;
测试 :
show triggers;-- 插入数据到tb_user
insert into tb_user(id, name, phone, email, profession, age, gender, status,
createtime) VALUES (26,'三皇子','18809091212','erhuangzi@163.com','软件工
程',23,'1','1',now());
测试完毕之后,检查日志表中的数据是否可以正常插入,以及插入数据的正确性。
B. 修改数据触发器
create trigger tb_user_update_triggerafter update on tb_user for each row
begin insert into user_logs(id, operation, operate_time, operate_id, operate_params)
VALUES
(null, 'update', now(), new.id,
concat('更新之前的数据: id=',old.id,',name=',old.name, ', phone=',
old.phone, ', email=', old.email, ', profession=', old.profession,
' | 更新之后的数据: id=',new.id,',name=',new.name, ', phone=',
NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));end;
测试 :
-- 查看
show triggers ;
-- 更新
update tb_user set profession = '会计' where id = 23;
update tb_user set profession = '会计' where id <= 5;
测试完毕之后,检查日志表中的数据是否可以正常插入,以及插入数据的正确性。
C. 删除数据触发器
create trigger tb_user_delete_triggerafter delete on tb_user for each row 
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params)
VALUES
(null, 'delete', now(), old.id,
concat('删除之前的数据: id=',old.id,',name=',old.name, ', phone=',
old.phone, ', email=', old.email, ', profession=', old.profession));
end;
测试 :
-- 查看
show triggers ;
-- 删除数据
delete from tb_user where id = 26;
测试完毕之后,检查日志表中的数据是否可以正常插入,以及插入数据的正确性。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词