使用游标可以逐行处理结果集中的数据,使用游标可以查询、更改、删除数据。以下是游标的基本使用方法。例题涉及2张表:Student(sno, sname, sex, age),Book(bookNo,bookName, author, price, pub)。
--例1、使用游标遍历学生表中的记录,输出每个学生的学号姓名及学生数。
declare @sno char(10),@sname char(20),@mycount int
declare mycursor cursor for select sno,sname from student
open mycursor
fetch mycursor into @sno,@sname
select @mycount=0
while @@fetch_status=0
begin
select @mycount=@mycount+1
print '学号:'+@sno+'姓名:'+@sname
fetch mycursor into @sno,@sname
end
close mycursor
deallocate mycursor
print @mycount
go
--例2、使用游标更新学生表中的姓名。
declare @sno char(10),@sname char(20)
declare mycursor cursor for select sno,sname from student for update of sname
open mycursor
fetch mycursor into @sno,@sname
while @@fetch_status=0
begin
if @sno='98001' update student set sname='xxx' where current of mycursor
fetch mycursor into @sno,@sname
end
close mycursor
deallocate mycursor
go
--例3、使用游标删除图书信息。
Declare cursorBook cursor for
select bookNo, bookName from book for update
Open cursorBook
Fetch next from cursorBook
While @@fetch_status=0
Begin
delete from book where current of cursorBook
Fetch next from cursorBook
End
Close cursorBook
Deallocate cursorBook
go
--例1、使用游标遍历学生表中的记录,输出每个学生的学号姓名及学生数。
declare @sno char(10),@sname char(20),@mycount int
declare mycursor cursor for select sno,sname from student
open mycursor
fetch mycursor into @sno,@sname
select @mycount=0
while @@fetch_status=0
begin
select @mycount=@mycount+1
print '学号:'+@sno+'姓名:'+@sname
fetch mycursor into @sno,@sname
end
close mycursor
deallocate mycursor
print @mycount
go
--例2、使用游标更新学生表中的姓名。
declare @sno char(10),@sname char(20)
declare mycursor cursor for select sno,sname from student for update of sname
open mycursor
fetch mycursor into @sno,@sname
while @@fetch_status=0
begin
if @sno='98001' update student set sname='xxx' where current of mycursor
fetch mycursor into @sno,@sname
end
close mycursor
deallocate mycursor
go
--例3、使用游标删除图书信息。
Declare cursorBook cursor for
select bookNo, bookName from book for update
Open cursorBook
Fetch next from cursorBook
While @@fetch_status=0
Begin
delete from book where current of cursorBook
Fetch next from cursorBook
End
Close cursorBook
Deallocate cursorBook
go