游标则是处理结果集的一种机制吧,它可以定位到结果集中的某一行,多数据进行读写,也可以移动游标定位到你所需要的行中进行操作数据。
一般复杂的存储过程,都会有游标的出现,他的用处主要有:
create table Member
(
MemberId int primary key identity(1,1),
MemberAccount nvarchar(20) unique check(len(MemberAccount) between 6 and 12),
MemberPwd nvarchar(20),
MemberNickname nvarchar(20),
MemberPhone nvarchar(20)
)
insert into Member(MemberAccount,MemberPwd,MemberNickname,MemberPhone)
values('liubei','123456','刘备','4659874564')
insert into Member(MemberAccount,MemberPwd,MemberNickname,MemberPhone)
values('guanyu','123456','关羽','42354234124')
insert into Member(MemberAccount,MemberPwd,MemberNickname,MemberPhone)
values('zhangfei','123456','张飞','41253445')
insert into Member(MemberAccount,MemberPwd,MemberNickname,MemberPhone)
values('zhangyun','123456','赵云','75675676547')
insert into Member(MemberAccount,MemberPwd,MemberNickname,MemberPhone)
values('machao','123456','马超','532523523')
语法
declare 游标名称 cursor scroll
for select 字段1,字段2,字段3 from 表名
--创建游标
declare cursor_myName cursor scroll
for select MemberAccount from Member
--创建指向某行多列的数据
declare cursor_myName2 cursor scroll
for select MemberAccount as 用户名,MemberPwd as 密码,MemberNickname as 姓名 from Member
scroll为滚动游标 可进可退,不加scroll则为只进不退,且只能支持fetch next
--打开游标
open cursor_myName
--提前某一行的结果
fetch first from cursor_myName
fetch last from cursor_myName
fetch absolute 3 from cursor_myName
fetch relative 2 from cursor_myName
fetch next from cursor_myName
fetch prior from cursor_myName
--关闭游标
close cursor_myName
--删除游标
deallocate cursor_myName
fetch first from --第一行
fetch last from --最后一行
fetch absolute n from --从第一行开始数,到第n行(n为整数)
fetch relative n from --从游标的当前位置数,到第n行(n为整数)
fetch next from --当前位置的下一行
fetch prior from --当前位置的上一行
使用 例如:fetch first from 游标名称
--遍历游标
declare @info varchar(20)
fetch absolute 1 from cursor_myName into @info
--@@fetch_status:0提取成功,-1失败,-2 数据不存在
while(@@fetch_status=0)
begin
print '提取游标成功:'+@info
fetch next from cursor_myName into @info
end
语法:
--游标修改当前数据语法
Update 基表名 Set 列名=值[,...] Where Current of 游标名
--游标删除当前数据语法
Delete 基表名 Where Current of 游标名
--利用游标进行修改和删除
select * from Member
fetch absolute 1 from cursor_myName
update Member set MemberPwd='112233' where current of cursor_myName
fetch next from cursor_myName
delete Member where current of cursor_myName