游标
游标概念
游标是一种能从包括多个元素的集合中每次读取一个元素的机制
(可以把游标看作一个指针,把select查询结果集看作一张二维表格,用游标指向表格的任意一行,允许用户对该行数据进行处理)
游标分类:Transact-SQL游标,API服务器游标,客户游标
游标示意图:
表A | 表B | |
---|---|---|
游标指向位置——>第一行 | ————> | 第一行 |
第二行 | 第二行 | |
… | … | |
第n行 | 第n行 |
管理游标
(1)声明游标
declare 游标名称 scroll curson
for secect …
from 表名
where…
(2)打开游标
open 游标名称
(3)读取游标(先将游标指向表的数据读出来,然后将数据存到指定的变量中)
fetch 读取数据的位置 form 游标名称
into 变量名1,变量名2,变量名3,…
指定游标的位置:
游标位置 | 解释 |
---|---|
first | 读取游标中的第一行数据 |
last | 读取游标中的最后一行数据 |
prior | 读取游标当前位置的上一行数据 |
next | 读取游标当前位置的下一行数据 |
absulute n | 读取游标的第n行数据 |
pelative n | 读取游标当前位置之前(n为正)或之后(n为负)的的n行数据 |
(4)关闭游标
close 游标名称
(5)释放游标
deallocate 游标名称 (释放游标)
(6)游标系统变量与函数
@@cursor_rows返回值 | 说明 |
---|---|
n | 游标已被完全填充,返回n是游标的总行数 |
0 | 游标未打开 |
-1 | 游标为动态游标。 |
-m | 游标被异步填充,返回的-m是键集中的当前行数 |
fetch读取一行数据的状态:
@@fetch_status返回值 | 说明 |
---|---|
0 | fetch语句读取一行数据成功 |
-1 | fetch语句读取一行数据失败或者此元组不在结果集中 |
-2 | 被读取元组不存在 |
cursor-status确定是否游标或者结果集
@@cursor-status返回值 | 说明 |
---|---|
1 | 结果集至少有一行 |
0 | 结果集为空 |
-1 | 游标被关闭 |
-2 | 游标不可用 |
-3 | 指定游标不存在 |
– current of 是表示当游标前指针所指的行
close 游标名
deallocate 游标名
删除当前数据行:
declare from 表名
where current of 游标名
– current of 是表示当游标前指针所指的行
close 游标名
deallocate 游标名
use student
go
--声明游标
declare s_cur scroll cursor
for select * from s
for update of sno,sname
go
--打开游标
open s_cur
if @@ error=0
print '共有'+convert(nchar(3),@@cursor_rows)+'行学生记录'
--读取游标
fetch next from s_cur--游标当前位置下一行
declare @sno char(10)
declare @sname char(10)
declare @sex char(2)
declare @birthdate char(5)
declare @college char(10)
fetch absolute 10 from s_cur
into @sno,@sname,@birthdate,@sex,@college
print '第十行数据为:学号'+@sno+'姓名'+@sname+'生日'+@birthdate+'性别'+@sex+'学院'+@college
update S
set sno='S111',sname='kaka'
where current of s_cur
close s_cur
deallocate s_cur
go