当前位置:文档之家› 数据库实验四

数据库实验四

实验四——数据库编程
一、实验目的
1.掌握ODBC的配置;
2.能编写简单的存储过程和函数,并调用;
3.了解游标的使用。

二、实验预习内容
上机前请预习以下内容,并在空白处填写相应的步骤或命令。

1.编写存储过程并调用,请写出相应命令;
1)编写存储过程usp_get_stuinfo ,使用一个名为@xm能够传送进存储过程的参数。

允许以学生的姓名查询该生的基本信息;
create procedure usp_get_stuinfo @xm varchar(32)AS
select*
from students
where sname=@xm
p_get_stuinfo gfxrgs
2)调用存储过程查询姓名为“rcxaihj”同学的基本信息的语句;p_get_stuinfo rcxaihj
2.编写函数并调用,请写出相应命令;
1)定义内联表值函数Fun1,用于返回学时为指定值的课程基本信息;create function fun1(@xs int)
returns table
as return(
select*from courses
where hour=@xs
)
2)使用Fun1进行选择以获得学时为48的课程基本信息;
select*from dbo.fun1(48)
3)在查询语句中使用Fun1函数,查询选了课时为48的课程的学生姓名、课程名称、学时及成绩。

select sname,cname,hour,score from students,choices,courses
where choices.sid=students.sid and choices.cid=courses.cid and hour in(
select hour from fun1(48))
3.编写函数并调用,请写出相应命令;
1)编写标量函数Fun2,用于返回两个整数中的最大值;
create function Fun2(@a int,@b int)
returns int
as begin
declare@c int
if@a>@b
set@c=@a
else
set@c=@b
return@c
end
2)调用此函数,输出两个数中的最大值;
print dbo.fun2(11,66)
4.对teachers表进行如下复杂的逻辑操作:1)对工资低于3000元的教师增加300元工资;update teachers
set salary=salary+ 300
where salary<3000
2)对工资大于等于3000元且小于4000元的教师增加200元工资;update teachers
set salary=salary+ 200
where salary<4000 and salary>=3000
3)对工资大于等于4000元的教师减少200元工资。

update teachers
set salary=salary- 200
where salary>=4000
分别使用SQL语句和游标实现上述功能,并比较二者执行效率。

结束本次实验。

use school
declare @xh char(10)
declare tea_cursor cursor for select tid from t1
open tea_cursor
fetch next from tea_cursor into @xh
while@@fetch_status=0
begin
if(select salary from t1 where tid=@xh )<3000
update t1 set salary=salary+300 where tid=@xh
else if(select salary from t1 where tid=@xh )>=3000 and
(select salary from t1 where tid=@xh )<4000
update t1 set salary=salary+200 where tid=@xh
else
update t1 set salary=salary-200 where tid=@xh
fetch next from tea_cursor into @xh
end
close tea_cursor
deallocate tea_cursor
三、实验课后训练
1.掌握SQL SERVER中流控制语句及其它常用编程语句;
2.配置ODBC,通过其它DBMS访问SQL SERVER 中的SCHOOL数据库数据。

四、实验总结
1.SQL SERVER中变量声明的命令是什么?输出命令是什么?
变量声明:局部变量不需要声明,declar@变量名,空格,数据类型(声明变量)全局变量不需要声明
输出命令:select(查询命令)
2.SQL SERVER中实现分支和循环的语句分别是什么?
分支:用case 测试表达式
When 测试值1 then 结果表达式1
When 测试值2 then 结果表达式2
Else 结果表达式n+1
end
循环:用while 布尔表达式
Begin 语句序列1
Break语句序列2
Continue 语句序列3
end
3.内联表值函数、标量函数、存储过程有什么区别?
内联表值函数:用户定义表值函数返回表数据类型,没有函数主体,表是单个select语句的结果集
标量函数:标量函数返回一个确定的类型的标量值
存储过程:存储过程是大型数据系统中,一组为了完成特定功能的SQL语句集,经编译后存储在数据库中。

功能强大,限制少,不能直接引用返回值,用SELECT返回记录集。

4.实验总结(实验过程中出现的问题、解决方法、结果如何或其它)
对于现学的知识,还需进一步理清逻辑,不能死记模板模式,要学会灵活运用,举一反三。

才能从容应对。

相关主题