Sql Server -游标2
游标的作用便于提取单一数据(单个字段值,或者单行全部字段值)
1.创建一个单字段游标stfid
go
declare cs_stfid scroll cursor for select stfid from staff --scroll 定义滚动游标
2.打开游标
open cs_stfid
3.提取游标第一行数据
fetch first from cs_stfid
4.获取游标数据集行数
select @@currsor_rows
5.获取提取状态
select @@fetch_status --如果fetch 成功返回0,否则返回-1
6.获取第三行数据
fetch absolute 3 from cs_stfid
7.获取当前行下方第三行数据
fetch relative 3 from cs_stfid
8.提取上一行数据
fetch prior from cs_stfid
9.循环输出stfid字段值
go
declare @i int =1
declare @rows int
set @rows=@@cursor_rows
while (@i<=@rows)
begin
fetch absolute @i from cs_stfid
set @i+=1
end
go
10.关闭游标
close cs_stfid
11.删除游标
deallocate cs_stfid
12.创建一个全字段游标,并逐行输出
go
declare @cs_staff scroll cursor for select * from staff
open cs_staff
fetch first from cs_staff
declare @i int=1
declare @rows int
set @rows = @@curosr_rows
while(@i<=@rows)
begin
fetch absolute @i from cs_staff
set @i+=1