Mysql 存储过程中使用游标循环读取临时表

游标

游标(cursor)是用于查看或者处理结果集中的数据的一种方法。游标提供了在结果集中一次一行或者多行前进或向后浏览数据的能力。

游标的使用方式

定义游标:declare 游标名称 cursor for table;(table也可以是select出来的结果集)
打开游标:open 游标名称;
从结果集获取数据到变量:fetch 游标名称 into field1,field2;
执行语句:执行需要处理数据的语句
关闭游标:close 游标名称;

begin
  # 声明自定义变量
  declare c_stgid int;
  declare c_stgname varchar(50);
  # 声明游标结束变量
  declare done int default 0;

  # 声明游标 cr 以及游标读取到结果集最后的处理方式
  declare cr cursor for select name,stgid from stgsummary limit 3;
  declare continue handler for not found set done = 1;

  # 打开游标
  open cr;

  # 循环
  readloop:loop
    # 获取游标中值并赋值给变量
    fetch cr into c_stgname,c_stgid;
    # 判断游标是否到底,若到底则退出游标
    # 需要注意这个判断
    if done = 1 then
      leave readloop; 
    end if; 
    
      select c_stgname,c_stgid;
    
  end loop readloop;
  -- 关闭游标
  close cr;
end

声明变量declare语句注意点:

  • declare语句通常用来声明本地变量、游标、条件或者handler
  • declare语句只允许出现在begin…end语句中而且必须出现在第一行
  • declare的顺序也有要求,通常是先声明本地变量,再是游标,然后是条件和handler

自定义变量命名注意点:

自定义变量的名称不要和游标的结果集字段名一样。若相同会出现游标给变量赋值无效的情况。

临时表

临时表只在当前连接可见,当关闭连接时,mysql会自动删除表并释放所有空间。因此在不同的连接中可以创建同名的临时表,并且操作属于本连接的临时表。
与普通创建语句的区别就是使用 temporary 关键字

create temporary table stgsummary(
 name varchar(50) not null,
 stgid int not null default 0
);

临时表使用限制

  1. 在同一个query语句中,只能查找一次临时表。同样在一个存储过程中也不能多次查询临时表。但是不同的临时表可以在一个query中使用。
  2. 不能用rename来重命名一个临时表,但是可以用alter table代替
alter table orig_name rename new_name;
  • 临时表使用完以后需要主动drop掉
drop temporary table if exists stgtemptable;

存储过程中使用游标循环读取临时表数据

begin
## 创建临时表
create temporary table if not exists stgsummary(
 name varchar(50) not null,
 stgid int not null default 0
);
truncate table stgsummary;

## 新增临时表数据
insert into stgsummary(name,stgid)
select '临时数据',1

begin

# 自定义变量
declare c_stgid int;
declare c_stgname varchar(50);
declare done int default 0;

declare cr cursor for select name,stgid from stgsummary order by stgid desc limit 3;
declare continue handler for not found set done = 1;

-- 打开游标
open cr;
testloop:loop
	-- 获取结果
	fetch cr into c_stgname,c_stgid;
	if done = 1 then
		leave testloop; 
	end if; 
	
  
  select c_stgname,c_stgid;
	
end loop testloop;
-- 关闭游标
close cr;

end;
drop temporary table if exists stgsummary;
end;

最开始的时候,先创建临时表,再定义游标。但是存储过程无论如何都保存不了。直接报错you have an error in your sql syntax; check the manual that corresponds to your mysql server version for the right syntax to use near 'declare ...根本原因就是上面提到的注意点(declare语句只允许出现在begin...end语句中而且必须出现在第一行)。所以最后只能多个加一对begin...end进行隔开。

总结

以前写sql server的存储过程,没有仔细注意过这个问题,定义变量一般都在程序中部,mysql就想当然的随便写,最后终于踩坑了。这两个语法上差别不大,但是真遇到差别还是挺突然的。不过也好久没有写sql语句,有点生疏了啊。还是赶紧把坑给记下来,加深下印象吧。

以上就是mysql 存储过程中使用游标循环读取临时表的详细内容,更多关于mysql 游标循环读取临时表的资料请关注www.887551.com其它相关文章!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐