SQL server之存储过程练习

 对应于student数据库

(1)  创建一个无参存储过程StuScoreInfo,查询以下信息:学号,姓名,性别,课程名称,考试成绩.

use Student

go

create proc StuScoreInfo

as select student.sno,sname,ssex,cname,sc.gradefrom student,course,sc

wherestudent.sno=sc.sno and course.cno=sc.cno

go

exec StuScoreInfo

(2)  创建一个带参数的存储过程stu_info,该存储过程根据传入的学生编号在student表中查询此学生的信息.

CREATE PROCstu_info

@NAME VARCHAR(20)

AS

SELECT *

FROM Student

WHERE Sname=@NAME

GO

EXEC stu_info '李勇'

(3)  创建一个带参数的存储过程StuScoreInfo2,该存储过程根据传入的学生编号和课程名称查询以下信息:姓名,课程名称,考试成绩.

CREATE PROCStuScoreInfo2

@NAME1VARCHAR(20),

@NAME2VARCHAR(20)

AS

SELECTsname,cname,grade

FROMstudent,course,sc

WHEREstudent.sno=sc.sno and course.cno=sc.cno and  student.sno=@NAME1 andcourse.cname=@NAME2

GO

EXECStuScoreInfo2 '201215121','数据库'

(4)  编写带参数的存储过程,根据传入的课程名称统计该课程的平均成绩.

create procTheAvg

@NAME VARCHAR(20)

as

select AVG(Grade)平均值 from Course,SC

wheresc.Cno=Course.cno and Course.Cname=@NAME

go

exec TheAvg '数学'

(5)   查询选了某门课的选课人数(使用输出参数)

create proc TheNum

@course varchar(20) output,

@num int output

as

select @course=Cname,@num=count(*) from Course,SC

where sc.Cno=Course.cno 

group by Cname

go

declare @name char(20),@num char(20)

exec TheNum  @name output,@numoutput

select @name ,@num

(6)   根据各种错误设置不同的返回代码值。查询指定学号的学生的考试平均成绩,1,执行成功,0,未指定学号,2指定的学号不存在,3指定的学号没有选课。

create proc TheOver(@sno varchar(20))

as

  

 if not exists(select * fromStudent where Sno =@sno)

begin

         print '2指定的学号不存在'

end 

 else if not exists(select *from Student where @sno not in(select Sno from Course))

begin

         print '3指定的学号没有选课'

end 

 else if exists(select * fromSC where Sno=@sno)

begin

         select AVG(Grade) 平均值 from SC where Sno=@sno

         print '1执行成功了'

end

      

 else

begin

         print '0未指定学号'

end

go

exec TheOver '200215121'  

 


猜你喜欢

转载自blog.csdn.net/yu_m_k/article/details/80545110