MySQL 存储过程游标

一、创建游标

游标用declare语句创建。如下面的例子所示:

create procedure test2()
begin
    declare cursorTest cursor for select * from allIntersection;
end;

二、打开、关闭游标

  • 打开游标
    open cursorTest;  
  • 关闭游标
    close cursorTest;  

    close 释放游标使用的所有内部内存和资源,因此在每个游标不再需要时都应该关闭。在一个游标关闭后,如果没有重新打开,则不能使用它。但是,声明过的游标不需要再次声明,用 open 语句打开它就可以了。

三、使用游标数据

在一个游标被打开后,可以使用 fetch 语句分别访问它的每一行。fetch 语句指定检索什么数据(所需的列),检索出来的数据存储在什么地方。它还向前移动游标中的内部行指针,使下一条 fetch 语句检索下一行(不重复读取同一行)。

create procedure test3()
begin
    declare o int;            -- 声明一个局部变量
    declare cursorTest3 cursor for select ID from allintersection; -- 声明一个游标 
    open cursorTest3; -- 打开游标 
    fetch cursorTest3 into o; -- 获取Inter
    sectionName close cursorTest3; -- 关闭游标 
end;

其中 fetch 用来检索当前行的 IntersectionName 列(将自动从第一行开始)到一个名为 o 的局部声明的变量中。对检索出的数据部做任何处理

四、式例

复制代码
create procedure test4()
begin
    declare done boolean default 0;
    declare o int;            -- 声明一个局部变量
    declare cursorTest4 cursor for select ID from allintersection;-- 声明一个游标 
    declare continue handler for sqlstate '02000' set done=1; 
    open cursorTest4; -- 打开游标  
    repeat   -- 遍历所有的行
      fetch cursorTest4 into o; -- 获取IntersectionName 
    until done end repeat;  -- 结束循环 
    close cursorTest4; -- 关闭游标
 end;
复制代码

 与 test3 不同的是,这个例子中的 fetch 是在 repeat 内,因此它反复执行到 done 为真( until done end repeat; 规定)。为使它起作用,用一个default 0(假,不结束)定义变量done。那么,done怎样才能在结束时被设置为真呢?答案是用以下语句:

declare continue handler for sqlstate '02000' set done=1;  

这条语句定义了一个 continue handler,它是在条件出现时被执行的代码。这里,它指出 sqlstate '02000'出现时,set done=1。sqlstate '02000'是一个未找到条件,当repeat 由于没有更多的行供循环而不能继续时,出现这个条件。

 

复制代码
create procedure `test5` ()
begin
-- 需要定义接收游标数据的变量 
  declare a char(16);
  -- 游标
  declare cursorTest5 cursor for select i from t;
  -- 遍历数据结束标志
  declare done int default false;
  -- 将结束标志绑定到游标
  declare continue handler for not found set done = true;
  -- 打开游标
  open curosrTest5;
  
  -- 开始循环
  read_loop: loop
    -- 提取游标里的数据,这里只有一个,多个的话也一样;
    fetch cursorTest5 into a;
    -- 声明结束的时候
    if done then
      leave read_loop;
    end if;
    -- 这里做你想做的循环的事件

    insert into t values (a);

  end loop;
  -- 关闭游标
  close curosrTest5;

end
复制代码

注意,变量的定义不要和你的select的列的键同名!不然,fetch into 会失败!

posted @   TannerBG  阅读(1559)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· DeepSeek处理自有业务的案例:让AI给你写一份小众编辑器(EverEdit)的语法着色文件
点击右上角即可分享
微信分享提示