游标

来源:互联网 发布:阿里云cdn加速服务 编辑:程序博客网 时间:2024/04/29 18:41

游标

--为什么要使用游标?

select * from Student

为了逐一地读取结果集中的每条记录;

 

--什么是游标?

总是与一个select语句相关联;

由结果集和指向结果中记录的位置指针来组成;

 

--如何使用游标?

(1)声明游标(2)打开游标(3)从游标中读取数据fetch first | last | next | prior | absolute n| relative nfrom 游标名into @变量1, @变量2,...(4)关闭游标(5)释放游标资源


 

--演示1-- (1)声明游标declare cur_Student cursor  for select Sno, Sname, Sage from Student-- (2)打开游标open cur_Student-- (3)从游标中读取数据declare @Sno char(5), @Sname char(6), @Sage intfetch next from cur_Student into @Sno, @Sname, @Sagewhile @@fetch_status  = 0begin       print '学号:' + @Sno + '姓名:' + @Sname + '年龄:' + Cast(@Sage as char(2))       if @Sage <20              print '该生还未成年!'       fetch next from cur_Student into @Sno, @Sname, @Sageend-- (4)关闭游标close cur_Student-- (5)释放游标资源deallocate cur_Student --演示2:游标嵌套declare cur_Student cursor  for select Sno, Sname, Sage from Student-- (2)打开游标open cur_Student-- (3)从游标中读取数据declare @Sno char(5), @Sname char(6), @Sage int, @Cname varchar(20)fetch next from cur_Student into @Sno, @Sname, @Sagewhile @@fetch_status  = 0begin       print '学号为:' + @Sno + '的学生' + @Sname + '选课了如下课程:'       declare cur_SC cursor for select Cname from Course, SC where Course.Cno = SC.Cno and Sno = @Sno       open cur_SC       fetch next from cur_SC into @Cname         while @@fetch_status = 0       begin              print @Cname              fetch next from cur_SC into @Cname       end       close cur_SC       deallocate cur_SC       fetch next from cur_Student into @Sno, @Sname, @Sageendclose cur_Studentdeallocate cur_Student