一、创建游标

游标用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 ;
declare o int; -- 声明一个局部变量
declare cursorTest4 cursor for select ID from allintersection;-- 声明一个游标
declare continue handler for sqlstate '' set done=;
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 '' set done=;  

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

create procedure `test5` ()
begin
-- 需要定义接收游标数据的变量
declare a char();
-- 游标
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 会失败!

最新文章

  1. vtkTubeFilter实例
  2. zookeeper分布式锁实现
  3. leetcode pow(x,n)实现
  4. Struts+Hibernate+Spring实现用户登录功能
  5. memcache相同主域名下的session共享
  6. gameui-for-phaser-js更新到最新版本
  7. Application tried to present a nil modal view controller on target “Current View Controller”解决方案
  8. 【学习笔记】Xcode常见设置
  9. windows10和ubuntu16.04双系统下时间不对的问题
  10. MT9v024总结
  11. FileUtil
  12. EGit使用教程:第一篇 添加工程到版本控制
  13. 话说TP框架里的Vendor这目录是干什么用的啊?类库扩展thinkphp3.1版本
  14. 日志分析工具Log Parser介绍
  15. RC terms.
  16. [R] Lexical & Dynamic Scoping / Execution & Calling environments / Closures
  17. 基于Python项目的Redis缓存消耗内存数据简单分析(附详细操作步骤)
  18. third party sales process 继续说
  19. php,微信公众号,获取用户地理位置 定位 经纬度
  20. Java switch 枚举

热门文章

  1. 创建线注记LineElement
  2. Google 地图 API V3 之控件
  3. CPU
  4. C++ ## ... 实用
  5. HTML5的属性
  6. python基础知识
  7. PHP如何快速读取大文件
  8. Windows环境配置HTTP服务(Windows + Apache + Mysql + PHP)
  9. iOS开发——高级篇——iOS中常见的设计模式(MVC/单例/委托/观察者)
  10. [Linux]Linux系统调用列表