1. 使用游标
创建游标
create procedure processorders()
begin
declare ordernumbers cursor for select order_num from orders;
end;
打开游标
open ordernumbers;
关闭游标
close ordernumbers;
创建带声明的游标
create procedure processorders()
begin
-- declare the cursor
declare ordernumbers cursor for select order_num from orders;
-- open the cursor
open ordernumbers;
-- close the cursor
close ordernumbers;
end;
使用游标数据
create procedure processorders()
begin
-- declare local variable
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;
使用游标检索循环数据
create procedure processorders()
begin
-- declare local variable
declare done boolean default 0;
declare o int;
-- declare the cursor
declare ordernumbers cursor for select order_num from orders;
-- declare continue handler
declare continue handler for sqlstate '02000' set done = 1;
-- open the cursor
open ordernumbers;
-- loop through all rows
repeat
-- get order number
fetch ordernumbers into o;
-- end of loop
until done end repeat;
-- close the cursor
close ordernumbers;
end;
使用游标检索循环数据保存到表中(question)
create procedure processorders()
begin
-- declare local variable
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 result
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, l, 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;
select * from ordertotals;
1. 游标(cursor):是一个存储在MySQL服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集。
游标主要用于交互式应用,其中用户需要滚动屏幕上的数据,并对数据进行浏览或做出更改。
游标只能用于存储过程和函数。
2. 使用游标的步骤:
1) 在能够使用游标前,必须声明(定义)它。这个过程实际上没有检索数据,它只是定义要使用的select语句。
2) 一旦声明后,必须打开游标以供使用。这个过程用前面定义的select语句把数据实际检索出来。
3) 对于填有数据的游标,根据需要去除(检索)各行。
4) 在结束游标使用时,必须关闭游标。
3. 在一个游标被打开后,可以使用fetch语句分别访问它的每一行。fetch指定检索什么数据(所需的列),检索出来的数据存储在什么地方。它还向前移动游标中的内部指针,使下一条fetch语句检索下一行(不重复读取同一行)。