美文网首页
MySql 存储过程与游标

MySql 存储过程与游标

作者: zshanjun | 来源:发表于2017-03-07 15:02 被阅读281次

有时候,需要在检索出来的行中前进或后退一行或多行。
这就是使用游标的烟瘾。游标是一个存储在MySQL服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。在存储了游标后,应用程序可以根据需要滚动或浏览其中的数据。
注意:不像多数DBMS,MySQL游标只能用于存储过程(和函数)

create procedure processorders()
begin

-- declare local variables
declare done boolean default 0;
declare o int;
declare t decimal(8,2);

-- declare the cursor
declare ordernumbers cursor
for
select order_num from orders;

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

-- create a table to store the results
create table if not exists ordertotals
 (order_num int, total decimal(8,2));
 
-- open the cursor
open ordernumbers;

-- loop through all rows
repeat

  -- get order number
  fetch ordernumbers into o;
  
  -- get the total for this order
  call ordertotal(o, 1, t);
  
  -- insert order and total into ordertotals
  insert into ordertotals(order_num, total)
  values(o, t);
  
  -- end of loop
  until done end repeat;
  
  -- close the cursor
  close ordernumbers;
  
end;

//运行与查看结果
call processorders();

select * from ordertotals;

+-----------+--------+
| order_num | total  |
+-----------+--------+
|     20005 | 158.86 |
|     20009 | 40.78  |
|     20006 | 58.3   |
|     20007 | 1060   |
|     20008 | 132.5  |
|     20008 | 132.5  |
+-----------+--------+

在这个例子中,我们增加了另一个名为t的变量(存储每个订单的合计)。此存储过程还在运行中创建了一个新表,名为ordertotals。这个表将保存存储过程生成的结果。fetch取每个order_num,然后用call执行另一个存储过程(在上一篇博文里创建的)来计算每个订单的带税合计(结果存储到t)。最后,用insert保存每个订单的订单号和合计。


参考书籍:

  • MySQL必知必会

相关文章

  • MySql 存储过程与游标

    有时候,需要在检索出来的行中前进或后退一行或多行。这就是使用游标的烟瘾。游标是一个存储在MySQL服务器上的数据库...

  • 学习笔记

    python 对线程 python MySQLDB mysql 游标 存储过程

  • mysql 存储过程 游标 游标嵌套

    如何把多列的查询结果设置到变量中? 示例: 在存储过程中我觉得不要使用用户变量,除非一后面要使用这个变量。 存储过...

  • MySQL 游标的基本用法

    MySQL游标只能用于存储过程。使用游标的步骤:①在能够使用游标前,必须声明它。这个过程实际上没有检索数据,它只是...

  • mysql 存储过程之游标

    游标按我的理解就是用在sql编程中对查询结果集的解析,类比jdbc中的resultset对象。FETCH 一行游标...

  • MySQL 存储过程,获取使用游标查询的结果集

    MySQL 存储过程中,使用游标查询,返回的是结果集时,如何查看调用存储过程输出结果呢?解决方案:存储过程不返回数...

  • mysql存储过程 --游标的使用

  • MySQL存储过程之游标实战

    日前在解决一个项目需求时,没有什么好的方法,于是就来学习存储过程了,之前也是接触过,奈何年少贪玩,竟是全部又还给了...

  • 关于Mysql存储过程及游标的说明书

    我和mysql存储过程、游标犹如“形同陌路”,不得不记录以便以后查看。 本文是阅读《mysql必知必会》的读书...

  • 存储过程--游标

    存储过程 定义:简单来说就是一组sql语句集,功能强大,类似于Java中的方法。特性有输入输出参数、模块化,封装,...

网友评论

      本文标题:MySql 存储过程与游标

      本文链接:https://www.haomeiwen.com/subject/rfumgttx.html