文章目录
- 什么是游标?
- 在哪里用游标?
- 为什么用游标?
- 游标如何使用?
什么是游标?
游标是SQL 的一种数据访问机制。
在哪里用游标?
当数据库的某项或多列数据需要进行检索或依据条件进行修改时,可以使用游标。
为什么用游标?
游标简单的看成是查询的结果集的一个指针,可以根据需要在结果集上面来回滚动,浏览需要的数据。
游标如何使用?
根据价格为价格等级设置标签。小于50价格便宜,50-100价格中等,大于100价格昂贵。
先定义一张Book表:
| 列名 | 数据类型 | 数据规范 |
|---|---|---|
| ID | int | 书编号,主键自增 |
| Name | nvarchar(50) | 书名 |
| Price | decimal(18, 2) | 价格 |
| Levels | varchar(10) | 价格等级 |
然后填充数据:

新建查询:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | --定义一个游标 declare cur_Set_Lve cursor for select id,Price from EnRole.dbo.Books --打开游标 open cur_Set_Lve declare @id int declare @price decimal(18,0) --获取数据 id,Price fetch next from cur_Set_Lve into @id,@price --循环获取 while(@@FETCH_STATUS=0) --@@fetch_status是MicroSoft SQL SERVER的一个全局变量 --其值有以下三种,分别表示三种不同含义:【返回类型integer】 --0 FETCH 语句成功 ---1 FETCH 语句失败或此行不在结果集中 ---2 被提取的行不存在 begin if(@price<50) update EnRole.dbo.Books set Levels='价格便宜' where ID=@id else if(@price<100) update EnRole.dbo.Books set Levels='价格适中' where ID=@id else update EnRole.dbo.Books set Levels='价格昂贵' where ID=@id fetch next from cur_Set_Lve into @id,@price end --关闭游标 close cur_Set_Lve --释放游标 deallocate cur_Set_Lve |
执行之后,数据如下:
