游标

游标(cursor)是一个存储在MySQL服务器上的数据库查询,不是select语句,而是被该语句检索处理的结果集,在存储了游标后,应用程序可以根据需要滚动或浏览其中的数据。用于交互式应用
游标只能用于存储过程(和 函数)
使用游标步骤:

  1. 声明(定义)游标,此过程不检索数据,只是定义select语句
  2. 必须打开游标以供使用,此过程用定义的select检索数据
  3. 对于填有数据的游标,根据需要取出(检索)各行
  4. 结束游标使用时,必须关闭游标

使用游标数据:fetch语句分别访问它的每一行

  1. -- 创建游标
  2. create procedure processorders()
  3. begin
  4. declare o int -- 声明变量
  5. declare ordernumbers cursor
  6. for
  7. select order_num from orders;
  8. open ordernumbers; -- 打开游标
  9. fetch ordernumbers into o; -- 检索单个行(第一行)
  10. close ordernumbers; -- 关闭游标
  11. end;