MySql 存储过程与游标

有时候,需要在检索出来的行中前进或后退一行或多行。
这就是使用游标的烟瘾。游标是一个存储在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必知必会
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 读《sql必知必会 第四版》随手做的笔记,写的比较乱,可读性并不好,读的是中文版,翻译过来的感觉有点怪怪的。...
    _老徐_阅读 687评论 0 0
  • 数据库就是以一个以某种有组织的方式存储的数据集合 MySql主键规则 不更新主键的值 不重用主键列的值 不在主键列...
    capo阅读 781评论 0 3
  • 学习mysql的几天,将笔记整理一下 SQL(Structured Query Language): 结构化查询语...
    年少懵懂丶流年梦阅读 995评论 0 2
  • 轰动世界的万国博览会于1855年在法国巴黎开暮了。 在博览会的一角有一件展品,大多数参观者都没有注意,却引起好几位...
    張楓阅读 3,009评论 0 1
  • 最近有人问我怎么学快速英语。 答:不可能。 只要宣传速成英语的都是骗子。学英语有高效的办法,但是没有速成的办法。有...
    洋杂汤阅读 2,111评论 6 18