文章详情页
mysql数据库存储过程之游标(光标cursor)详解
浏览:2日期:2023-07-05 19:48:16
目录mysql存储过程之游标(光标cursor)一、语法二、案例三、条件处理程序mysql存储过程-游标 CURSOR FOR总结mysql存储过程之游标(光标cursor)
游标是用来存储查询结果集的数据类型,在存储过程和函数中可以使用游标对结果集进行循环的处理。
游标的使用包括游标的声明、open、fetch和close。
一、语法#声明游标declare 游标名称 cursor for 查询语句;#开启游标open 游标名称;#获取游标记录fetch 游标名称 into 变量[,变量];#关闭游标close 游标名称;二、案例根据传入的参数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);#声明变量 declary upro varchar(100);#声明变量#声明游标记录符合条件的结果集 declare u_cursor cursor for select name,profession from tb_user where age <= uage; drop table if exists tb_user_pro; #tb_user_pro表如果存在,就删除。 create table if exists tb_user_pro( #if exists代表表存在就删除了再创建表 id int primary key auto_increment, name varchar(100), profession varchar(100) ); open u_cursor;#开启游标#while循环获取游标当中的数据 while true do fetch u_cursor into uname,upro;#获取游标中的记录 insert into tb_user_pro values(null,uname,upro);#将获取到的数据插入表结构中 end while; close u_cursor;#关闭游标end;#查询年龄小于30call p11(30);三、条件处理程序条件处理程序handler可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。
1、语法
declare handler_action handler for condition_value [,condition_value]... statement;handler_action
continue:继续执行当前程序exit:终止执行当前程序condition_value
SQLSTATE sqlstate_value:状态码,如02000SQLwarning:所有以01开头的SQLstate代码的简写not found:所有以02开头的SQLSTATE代码的简写SQLexception:所有没有被SQLwarning或not found捕获的SQLstate代码的简写2、解决报错
#创建一个存储过程create procedure p11(in uage int)begin declare uname varchar(100);#声明变量 declary upro varchar(100);#声明变量#声明游标记录符合条件的结果集 declare u_cursor cursor for select name,profession from tb_user where age <= uage;#声明一个条件处理程序,当满足SQL状态码为02000的时候,触发退出操作,退出的时候将游标关闭 declare exit handler for SQLSTATE '02000' close u_cursorl;#声明一个条件处理程序,当满足SQL状态码为02000的时候,触发退出操作,退出的时候将游标关闭 declare exit handler for not found close u_cursorl;drop table if exists tb_user_pro; #tb_user_pro表如果存在,就删除。 create table if exists tb_user_pro( #if exists代表表存在就删除了再创建表 id int primary key auto_increment, name varchar(100), profession varchar(100) ); open u_cursor;#开启游标#while循环获取游标当中的数据 while true do fetch u_cursor into uname,upro;#获取游标中的记录 insert into tb_user_pro values(null,uname,upro);#将获取到的数据插入表结构中 end while; close u_cursor;#关闭游标end;#查询年龄小于30call p11(30);mysql存储过程-游标 CURSOR FOR1、游标
游标是一个存储在MySQL服务器上的数据库查询,它不是一条select语句,而是被该语句所检索出来的结果集。
2、定义游标
这个过程并没有检索到数据,只是定义要使用的select语句
DECLARE t_cursor CURSOR FOR SELECT t.id FROM t_dept t;3、如果没有数据返回或者select出现异常,程序继续,并将变量done设为true
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=true;4、打开游标
open t_cursor;5、使用游标
使用fetch来取出数据
fetch t_cursor in variable;6、关闭游标
close t_cursor;过程:定义游标(使用游标前必须先定义游标)—》打开游标—》关闭游标
总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
排行榜