sql游标使用 sql游标使用

2016-06-11

use student_15
go
declare student_cur cursor
   for select * from student
go

declare @sid int
declare @sname varchar(20)
declare @ssex char(1)
declare @sage int
declare @classid int

open student_cur
   
fetch next from student_cur into @sid,@sname,@ssex,@sage,@classid
    while @@fetch_status=0
    begin
      print @sname
      fetch next from student_cur into @sid,@sname,@ssex,@sage,@classid
    end
close student_cur
deallocate student_cur
/*******************************

      说明:游标的操作(update)
*******************************/
use student_15
go
select * from student
go

declare student_cur cursor
    scroll   --游标的移动位置
    for select * from student
    for update of sname,sage
go   
declare @sid int
declare @sname varchar(20)
declare @ssex char(1)
declare @sage int
declare @classid int

open student_cur
   fetch first from student_cur into @sid,@sname,@ssex,@sage,@classid
     /*更新游标数据*/
   
update student set sage=19,sname='11' where current of student_cur
    while @@fetch_status =0    begin

          fetch next from student_cur into @sid,@sname,@ssex,@sage,@classid
         
          if @sid=1003   begin
           update student set sage=19,sname='11' where current of student_cur
          end
          
     end
close student_cur
deallocate student_cur

/*************游标操作删除***************/
use student_15
go

declare student_cur cursor
    scroll
    for select * from student
    for update of sid
go

declare @sid int
declare @sname varchar(20)
declare @ssex char(1)
declare @sage int
declare @classid int

open student_cur

      fetch first from student_cur into @sid,@sname,@ssex,@sage,@classid

      while @@fetch_status=0

         begin

      fetch next from student_cur into @sid,@sname,@ssex,@sage,@classid

      if @sid=1003
    
        begin
  
         delete student where current of student_cur
   
        end
     end
close student_cur
deallocate student_cur