有时候,需要在检索出来的行中前进或后退一行或多行。
这就是使用游标的烟瘾。游标是一个存储在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必知必会
网友评论