技术开发 频道

SQL SERVER 参考:游标(Cursor)的讲解与实例

  举例2:

  通过游标对读取的数据进行操作,并输出不同的结果:

declare @s_name varchar(20),@c_name VARCHAR(64),@sc_core int
declare my_cur cursor for select sname,cname,scgrade
from student s, course c, studentCourse sc WHERE s.sno=sc.sno AND c.cno=sc.cno
open my_cur
print space(27)+'2007年计算机专业考试系统'
fetch next from my_cur into @s_name,@c_name,@sc_core
while @@fetch_status=0
begin
    
if @sc_core<60
    
begin
        
print space(20)+@s_name+ @c_name +':不及格 '
    
end
    
else
    
begin
          
if @sc_core >=60 and @sc_core <70
          
begin
              
print space(20)+@s_name  + @c_name +':及格 '
          
end
          
else
          
begin
              
if @sc_core>=70 and @sc_core<80
              
begin
                  
print space(20)+@s_name + @c_name +':良好'
              
end
              
else
              
begin
                  
print space(20)+@s_name + @c_name +':优秀'
              
end
          
end
    
end
fetch next from my_cur into @s_name,@c_name,@sc_core
end
close my_cur
deallocate my_cur

  结果:
                             2007年计算机专业考试系统
                    Jack Dong                               C++ 程序设计:及格
                    Jack Dong                               操作系统:良好
                    Lucy Dong                               C++ 程序设计:优秀
                    Lucy Dong                               计算机组成原理:良好
                    Brezse Dong                             C++ 程序设计:优秀
                    Brezse Dong                             面向对象的程序设计方法:不及格
                    Andy Liu                                操作系统:不及格
                    Andy Liu                                计算机组成原理:优秀 

  使用游标时应注意的问题:
 
  (1) 尽管使用游标比较灵活,可以实现对数据集中单行数据的直接操作,但游标会在下面几个方面影响系统的性能:
  -使用游标会导致页锁与表锁的增加
  -导致网络通信量的增加
  -增加了服务器处理相应指令的额外开销

  (2) 使用游标时的优化问题:
  -明确指出游标的用途:for read only或for update
  -在for update后指定被修改的列

0
相关文章