游标
1.什么是游标?
游标是SQL 的一种数据访问机制。可以将游标简单的看成是查询的结果集的一个指针,可以根据需要在结果集上面来回滚动,浏览需要的数据。
2.游标的作用是什么?
查询数据,大多的语言都支持使用游标来检索SQL数据库中的数据,并保存查询的结果以供之后使用,比如我们在日常过程中需要重复处理容易个结果集,我们就可以选择只加载一次结果集,创建一个游标并反复使用,这样就比多次创建结果集效率要高的多。
游标的生命周期
3.游标的生命周期
包含有五个阶段:声明游标、打开游标、读取游标数据、关闭游标、释放游标。
4.怎么使用和创建游标?
首先创建一个测试表
Book表(书本表):
ID | Name | Price | levels |
---|---|---|---|
1 | JavaScript | 10.00 | 无 |
2 | 斗罗大陆 | 15.00 | 无 |
3 | 三国演义 | 200.00 | 无 |
4 | 水浒传 | 25.00 | 无 |
5 | 红楼梦 | 300.00 | 无 |
6 | 斗破苍穹 | 75.00 | 无 |
案例使用:价格<50,levels改为便宜,50<价格<100,levels为一般,价格>100,levels为昂贵。
1)相关语法
--创建游标
declare cursor_name(游标名称) cursor(游标关键字)
for
select ID,Price from Book --相关sql语句
--打开游标
open cursor_name(游标名称)
--获取数据
declare @id int --定义变量
declare @price decimal(18,2) --定义变量
fetch next from cur_set_levels into @id,@price --获取id和price
--关闭游标
close cursor_name(游标名称)
--释放游标
deallocate cursor_name(游标名称)
2)演示案例
--创建游标
declare cur_set_levels cursor
for
select ID,Price from Book
--打开游标
open cur_set_levels
--获取数据
declare @id int
declare @price decimal(18,2)
fetch next from cur_set_levels into @id,@price
while(@@FETCH_STATUS=0)
begin
if(@price<50)
update Book set Levels='便宜' where ID=@id
else if(@price<100)
update Book set Levels='中等' where ID=@id
else
update Book set Levels='贵' where ID=@id
fetch next from cur_set_levels into @id,@price
end
--关闭游标
close cur_set_levels
--释放游标
deallocate cur_set_levels
执行代码前
执行代码后