一.实验目的:
掌握游标的声明、游标打开、标数据的提取、游标的关闭和游标的释放
掌握标量值函数的定义与调用
掌握内联表值函数的定义与调用
掌握多语句表值函数的定义与调用
二.实验内容:(所有题写到实验报告中)
1.使用游标打印OrderManagement库中各订单中的总金额,要求按总金额降序排,打印格式如下:
2.使用游标提取学生课程库中3-105课的前三名学生的信息和后三名学生的信息,包括学号、姓名、课程名和成绩。(不考虑成绩相同的情况)
3.使用游标修改OrderManagement库的order_detail表中订单号为***的单价最高的器件的单价和单价最低的器件的单价。
4.创建标量函数,计算指定课程号的课程的平均成绩,然后调用该函数查询某门课的平均成绩。
5.创建内联表值函数,查询指定学号的学生的选课情况(包括学号、姓名、课程号和成绩),然后调用该函数查询某位学生的选课情况,再调用该函数将该生某门课的成绩改为100,重新查询该生成绩检查一下改过来了吗。
6.创建多语句表值函数,查询指定课程号的学生的选课情况(包括学号、姓名和成绩),并将选了该课的学生成绩提高5分,然后调用该函数查询某门课的学生的选课及成绩修改情况。(之前先查询一下该课的成绩以便与调用函数后的成绩作对比。)
use OrderManagement
go
declare @num char(6),@smoney int
declare money cursor
for
select 订单号,sum(单价*数量) as 总金额 from order_detail group by 订单号 order by 总金额 desc
open money
FETCH NEXT FROM money INTO @num,@smoney
PRINT '订单号总金额'
PRINT '-------------'
WHILE @@FETCH_STATUS = 0
BEGIN
--打印一行数据
PRINT @num+' ' +CAST(@smoney AS char)
--提取下一行数据
FETCH NEXT FROM money INTO @num,@smoney
END
close money
deallocate money
go
---2
use stuinfo
go
declare sdegree SCROLL cursor
for
select score.sno,sname,cname,degree from score,student,course where score.cno = '3-105' and score.sno=student.sno and score.cno = course.cno order by degree desc
open sdegree
FETCH FIRST FROM sdegree
FETCH ABSOLUTE 2 FROM sdegree
FETCH ABSOLUTE 3 FROM sdegree
FETCH LAST FROM sdegree
FETCH RELATIVE -1 FROM sdegree
FETCH RELATIVE -2 FROM sdegree
CLOSE sdegree
DEALLOCATE sdegree
---3 使用游标修改OrderManagement库的order_detail表中订单号为***的单价最高的器件的单价和单价最低的器件的单价
use OrderManagement
go
declare @maxmoney int,@minmoney int
declare test scroll cursor
for
select 单价 from order_detail where 订单号='OR-03C' order by 单价 desc
open test
FETCH FIRST FROM test INTO @maxmoney
FETCH LAST FROM test INTO @minmoney
update order_detail set 单价=9999 where 单价=@maxmoney
update order_detail set 单价=0 where 单价=@minmoney
CLOSE sdegree
DEALLOCATE sdegree
---4 创建标量函数,计算指定课程号的课程的平均成绩,然后调用该函数查询某门课的平均成绩
use stuinfo
go
CREATE FUNCTION avg_degree(@cno char(5))
returns int
as
begin
declare @avgg int
select @avgg=AVG(degree) from score where cno=@cno
return @avgg
end
select dbo.avg_degree('3-105')
---5
use stuinfo
go
create function Fun_GetList(@sno char(5))
returns table
return(
select student.sno,student.sname,course.cno,score.degree
from student,course,score
where student.sno=score.sno and score.cno=course.cno
and student.sno=@sno
)
select * from dbo.Fun_GetList('101')
update dbo.Fun_GetList('101') set degree=100 where cno='3-105'
select * from dbo.Fun_GetList('101')
---6
create function dyjhs(@cno char(6))
returns @ss table(sn int,sname char(6),degree int)
begin
insert @ss select student.sno,sname,degree = degree + 5
from student,score
where student.sno = score.sno and score.cno = @cno
return
end
select * from dyjhs('3-105')