我们先来看看存储过程的概念:
•概念简介
–存储过程(stored procedure)是一组为了完成特定功能的SQL语句集合,经编译后存储在服务器端的数据库中,利用存储过程可以加速SQL语句的执行。
•优点
–提高应用程序的通用性和可移植性:存储过程创建后,可以在程序中被多次调用,而不必重新编写该存储过程的SQL语句。并且数据库专业人员可以随时对存储过程进行修改,且对程序源代码没有影响,这样就极大的提高了程序的可移植性。
–可以提高SQL的速度,存储过程是编译过的,如果某一个操作包含大量的SQL代码或分别被执行多次,那么使用存储过程比直接使用单条SQL语句执行速度快的多。
–减轻服务器的负担:当用户的操作是针对数据库对象的操作时,如果使用单条调用的方式,那么网络上还必须传输大量的SQL语句,如果使用存储过程,则直接发送过程的调用命令即可,降低了网络的负担。
存储过程语法
创建/修改存储过程
CREATE/ ALTER PROC procedure_name
@parameter data_type,--输入参数
@parameter data_type OUTPUT --输出参数
AS
Begin
SQL 语句
End
删除存储过程
Drop Proc procedure_name
无参数存储过程
•创建名为 GetStuCou 的无参数存储过程
create procedure GetStuCou
as
begin
select *
from Student s
left join Score c on s.sno=c.sno11
end
•执行名为 GetStuCou 的无参数存储过程
exec GetStuCou
有输入参数的存储过程
create procedure GetStuCou_In
@StuNo nvarchar(64)='001' --设置默认值
as
begin
select * from Student where sno=@StuNo
end
•不传参数,即使用默认值
execute GetStuCou_In
•传参
execute GetStuCou_In '002'
有输入输出参数
create procedure GetStuCou_Out
@StuNo nvarchar(64),
@Height nvarchar(32) output
as
begin
if(@StuNo is not null and @StuNo <> '')
begin
select @Height=sage
from Student
where sno=@StuNo
end
else
begin
set @Height='18'
end
end
•执行存储过程
declare @count int
execute GetStuCou_Out '005',@count output
select @count
然后,我们要用存储过程实现可以通过班级查询不同科目的平均分,并统计该班级男生数量
实现代码:
if exists(select * from sysobjects where name='GetAvgAndCountByClass')
drop proc GetAvgAndCountByClass
go
create procedure GetAvgAndCountByClass(
@Sclass nvarchar(100),
--@Ssubject nvarchar(100),
@SsubjectAvg int output,
@Count int output
)
as
begin
if(@Sclass is not null and @Sclass <> '')
begin
select s1.Sclass 班级,s2.Ssubject 学科,avg(s2.Sgrade)平均分
from student as s1 inner join score as s2 on s1.Sno=s2.Sno
where s1.Sclass=@Sclass --and s2.Ssubject=@Ssubject
group by s1.Sclass,s2.Ssubject
set @Count= (select count(*)
from student s
where s.Sclass=@Sclass and s.Ssex='男')
end
else
begin
set @Count= 0
end
end
go
declare @subjectAvg int,@countMan int
execute GetAvgAndCountByClass @Sclass='一班',@SsubjectAvg=@subjectAvg output,@Count=@countMan output
select @countMan 男生数量
运行结果: