MySQL游标使用

游标是一个存储再MySQL服务器上的数据查询,它不是

一条select语句,而是被某一条select语句检索出来的结果集。

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


简单一点理解,就像高级语言中的集合,用来存储一个结果集的东西。

##这里要注意一点:MySQL游标只能用于存储过程(和函数)

直接通过一个sql脚本来看:

对于存储过程还不知道的可以参看我这篇博客:存储过程初探

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;
	
	--delare continue handler
	declare continue handler for sqlstate '02000' set done = 1;
	
	--create a table to store the results
	create table if not exists ordertotals(
	ordernum int,
	total decimal(8,2)
	);
	
	--open the cursor
	open ordernumbers;
	
	--loop through all rows
	repeat
		--get order numbers
		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;




如上游标的用法:

创建游标

declare ordernumbers cursor
for
select order_num from orders;


就是把查询到的某一列的数据都放到order里面去。

使用游标前需要打开游标:

open ordernumbers;
用完后关闭使用close关键字;



循环语句使用技巧:

这条语句定义了一个continue handler,它是在条件出现时被执行的代码。

这里,它指出当sqlstate '02000'出现时,set done =1,

而sqlstate '02000'是一个未找到条件,当repeat由于没有更多的行提供循环

而不能继续时,就会出现这个条件。













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值