声明游标格式
declare 游标名 cursor
for 查询结果集 for update of 列名
打开游标 open 游标名
提取数据 fetch next from 游标名
关闭游标 close 游标
释放游标 deallocate 游标名
所用到的表
–迅雷提取
链接:https://pan.xunlei.com/s/VMOQuiLehNmu2_YoG8g42iuLA1
提取码:7wwu
create database Hero
use Hero
go
create table basexi
(
sno char(20) primary key,
sname char(20),
sex char(2),
sage int,
sclass char(20)
)
create table wq
(
cno char(20) primary key,
cname char(20),
)
create table wl
(
sno char(20) foreign key references basexi(sno),
cno char(20) foreign key references wq(cno),
grade int,
)
select * from basexi
select * from wl
select * from wq
--创建存储过程实现显示第一,二条记录
go
create procedure proc1
as
declare cur1 scroll cursor
for
select * from basexi
open cur1
select '这是第英雄的信息' as '提示'
fetch next from cur1
fetch next from cur1
close cur1
deallocate cur1
exec proc1
--通过游标修改值
go
alter procedure proc2 @sclass char(30)
as
declare cur1 scroll cursor
for
select * from basexi
where sclass = @sclass
for update of sage,sex
open cur1
fetch lat from cur1
update basexi set sage = 20
where current of cur1
close cur1
deallocate cur1
exec proc2 '刘氏集团'
--提取数据并保存在指定变量中
go
ALTER procedure proc4
as
declare pf cursor for
select sname,cname,grade from basexi a,wq b,wl c
where a.sno = c.sno and b.cno = c.cno
for update
open pf
declare @name char(20),@cname char(20),@score int
while @@FETCH_STATUS = 0
begin
fetch next from pf into @name,@cname,@score
if @score >= 90
select @name 姓名,@cname 兵器,'优秀' 等级
else if @score >= 80
select @name 姓名,@cname 兵器,'良' 等级
else
select @name 姓名,@cname 兵器,'差' 等级
END
close pf
deallocate pf
exec proc4
总结:游标声明
declare 游标名 cursor [forward_only|scroll] for 查询语句
For update of 列名表
声明游标中参数介绍
1、什么参数不带,相当于forward_only。利用fetch 提取数据时只能用next向下移动一条记录。
2、当带scroll参数时,利用fetch提取数据时所有的操作都能使用
next 向下
Prior 向上
First 第一条
Last 最后一条
Relative n 相对当前行向下n条
Relative –n 相对当前行向上n条
Absolute n 从第一条开始移动n条
Absolute –n 从最后一条向上移动n条
3,for update 说明游标中的数据可以被修改和删除