《MySQL必知必会》--游标

游标

概念

游标(cursor)是一个存储在MySQL服务器上的数据库查询,它并不是一条SELECT语句,而是被该语句检索出来的结果集。

在存储了游标之后,应用程序可以根据需要滚动或浏览其中的数据。

游标主要用于交互式应用,其中用户需要滚动屏幕上的数据,并对数据进行浏览或更改。

MySQL游标只能用于存储过程和存储函数。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-- 在存储过程中创建游标
DELIMITER //
create procedure processorders()
begin
declare ordernumbers cursor for
select order_num from orders;

end //
DELIMITER ;

-- 删除该存储过程,以便重新创建
drop procedure processorders;

-- 在存储过程中创建以及使用游标
delimiter //
create procedure processorders()
begin

-- declare local variables
declare o INT;

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

-- open the cursor
open ordernumbers;

-- get order number
fetch ordernumbers into o;

-- close the cursor
close ordernumbers;
end //
delimiter ;

总结

最后这几章就是又不常用又难理解的东西,先大致学习一下,等以后熟悉了基础再回来解决遗留问题。