游标:其实跟咱们用select读取一个表的意思差很少,只不过它像指针,一行一行的读取,指到哪一行就读取哪一行的数据。数据库
实例:数据结构
/** 1. 声明一个只读游标,数据来源是表Student的全部状况,按照名字排序,打开该游标,查看全局变量@@cursor_rows,提取第1行数据 ,第2行数据,第3行数据,试试可否把当前行的年龄改成50,可否提取最后一行数据, **/ declare s_sur cursor for select *from Student order by SName for read only open s_sur select @@CURSOR_ROWS fetch next from s_sur update Student set SAge ='50' where current of s_sur fetch last from s_sur close s_sur /**2. 声明一个可滚动(SCROLL)的只读游标,数据来源是选择表Student的姓名和学号,按照名字排序, 打开该游标,查看全局变量@@cursor_rows,提取第5行数据,并把数据的学号和姓名赋予给变量学号和姓名(对比上一题理解SCROLL的做用); */ declare s_sur1 scroll cursor for select sno,sname from Student order by SName for read only declare @sno char(5),@sname varchar(8) open s_sur1 select @@CURSOR_ROWS fetch absolute 5 from s_sur1 into @sno,@sname select @sno SELECT @sname close s_sur1 /**3. 声明一个具备灵敏性(INSENSITIVE)的游标,数据来源是表Student的学号姓名,按照名字排序,打开该游标,定义两个变量, 使用全局变量@@FETCH_STATUS(0 FETCH 语句成功,-1 FETCH 语句失败或此行不在结果集中,-2 被提取的行不存在)与WHILE循环遍 历游标所在数据集赋值给两个变量,并print变量。*/ declare s3_surl insensitive scroll cursor for select sno,sname from Student order by SName open s3_surl declare @sno1 char(5),@sname1 varchar(8) declare @x int select @x= @@CURSOR_ROWS print @x while(@x>0) begin set @x=@x-1 fetch next from s3_surl into @sno1,@sname1 print @sno1 print @sname1 end close s3_surl /**4. 声明一个可更新的游标,数据来源是表Student的全部状况,打开该游标,提取第1行数据,并把当前行的年龄改成50, 而后查看基本表看是否已经修改;*/ declare s5_surl scroll cursor for select *from Student for update of sage open s5_surl fetch first from s5_surl update Student set SAge=50 where current of s5_surl close s5_surl /**5. 利用游标查询所有学生的选课信息,显示格式以下所示:**/ declare stu scroll cursor for select s.SNo,sname ,cname,score from Student s,sc,course c where s.SNo=sc.SNo and sc.CNo=c.CNo group by s.SNo,sname ,cname,score open stu declare @sno2 char(5),@sno3 char(5),@sname2 varchar(8),@cname varchar(40) declare @score numeric(3,1) declare @x1 int select @x1=@@CURSOR_ROWS set @sno3='0' while(@x1>0) begin set @x1=@x1-1 fetch next from stu into @sno2,@sname2,@cname,@score if(@sno3!=@sno2) begin print @sno2+' '+@sname2 end print @sname2+' '+'选修了:'+@cname+' 成绩为:'+convert(char(4),@score) set @sno3=@sno2 end close stu /*6. 试试看能不能声明一个有SCROLL或INSENSITIVE的可更新的游标。 **/ declare s1 insensitive scroll cursor for select sno,sname from Student order by SName for update of stage /**7. 统计“数据结构”课程考试成绩的各分数段的分布状况,即不及格、及格、中等、良好和优秀的人数。**/ select SUM(case when score>=0 and score <60 then 1 else 0 end )as 不及格, SUM(case when score >=60 and Score<75 then 1 else 0 end)as 中, SUM(case when score >= 75and Score<85 then 1 else 0 end)as 良, SUM(case when score >= 85 then 1 else 0 end)as 优秀 from sc where sc.CNo=(select cno from course where CName='数据结构')