文章目录
游标的使用分为5步:
1、声明游标
2、打开游标
3、读取游标中的数据
4、关闭游标
5、释放游标
容易出错的地方:
1、while里面写begin、end
2、更新值的时候用set或select
1、计算没有选课的学生人数
涉及到的表:student、sc
--1、声明游标
declare num_cursor cursor
for
select sno
from student
for read only
--2、打开游标
open num_cursor
--声明变量
declare @sno char(20), @num int
select @num = 0
--3、读取游标中的数据
fetch next from num_cursor
into @sno
while @@FETCH_STATUS = 0
begin
if not exists(select* from sc where Sno = @sno)
select @num = @num + 1
fetch next from num_cursor
into @sno
end
--打印未选课的学生人数
select @num
--4、关闭游标
close num_cursor
--5、释放游标
deallocate num_cursor
效果:
2、打印出每个科目的选课人数
涉及到的表: