Sql Server -游标2

发布时间 2023-08-19 09:21:43作者: KevinSteven

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