什么是游标?
游标是SQL 的一种数据访问机制。存储在MySQL 服务器上的数据查询,可以将游标简单的看成是查询的结果集的一个指针,可以根据需要在结果集上面来回滚动,浏览需要的数据。
如何声明游标
游标在使用前必须声明。
可以用DECLARE <游标名> CURSOR 进行声明
1:声明游标
2:打开游标
使用 OPEN 语句功能打开游标,实际上就是执行相对应的SELECT查询语句。
一般格式为: open <游标名>
3: 提取游标
FETCH 语句是从游标中提取特定的一行。使用游标完成相对应的操作。
4:关闭游标
使用 CLOSE 语句关闭游标。
5:释放游标
使用 DEALLOCATE 语句释放。
说明:
next–如果是在open后第一次执行fetch命令,则返回结果集的第一行,否则使游标的指针指向结果集的下一行,next是默认的选项。
prlor-返回结果集当前行的前一行.
flrst返回结果集的第一行
last返回结果集的最后一行
INTO-该语句的功能是把游标取出来的当前记录送入到主变量。
完整代码:
--声明游标
declare cur_cust_level Cursor
for select id,ConsumeAmount from Customers
--打开游标
open cur_cust_level
--浏览数据,取数据ID,ConsumeAmount
--取数据
declare @id int
declare @Cacount int
fetch next from cur_cust_level into @id,@Cacount
--循环往下
while (@@FETCH_STATUS=0)
begin
--修改消费等级
if(@Cacount<500)
update Customers set ConsumeLeve='低消费' where id=@id
else if(@cacount <1000)
update Customers set ConsumeLeve='中消费' where id=@id
else
update Customers set ConsumeLeve='高消费' where id=@id
fetch next from cur_cust_level into @id,@cacount
end
--关闭游标
close cur_cust_level
--释放游标
deallocate cur_cust_level
select *from Customers