游标的使用

什么是游标?
游标是SQL 的一种数据访问机制。
在哪里用游标?
当数据库的某项或多列数据需要进行检索或依据条件进行修改时,可以使用游标。
为什么用游标?
游标简单的看成是查询的结果集的一个指针,可以根据需要在结果集上面来回滚动,浏览需要的数据。
游标如何使用?
根据价格为价格等级设置标签。小于50价格便宜,50-100价格中等,大于100价格昂贵。
先定义一张Book表:
游标的使用
游标的使用
–定义游标
declare cur_set_lever CURSOR
for select id,Price from Books
–打开游标
open cur_set_lever
–获取数据。ID,Price
declare @id int
declare @price decimal(18,2)
fetch next from cur_set_lever into @id,@price
print @id
–循环获取
while(@@FETCH_STATUS=0)
begin
if(@price<50)
update book set Levels=‘价格便宜’ where [email protected]
else if(@price<100)
update book set Levels=‘价格中等’ where [email protected]
else
update book set Levels=‘价格昂贵’ where [email protected]
fetch next from cur_set_lever into @id,@price
end
–关闭游标
close cur_set_lever
–释放游标
open cur_set_lever
执行后 数据如下:
游标的使用