SQL:游标

声明游标格式
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 说明游标中的数据可以被修改和删除

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值