SQL语句之存储过程

SQL三类存储过程

SQL语句的存储过程主要有以下三种:

  1. 不含参数的
  2. 含有输入参数的
  3. 既含有输入参数,又含有输出参数的

我们通过下面三道例题来做详细的理解

不含参数的存储过程

查询每个学生的修课总学分,要求列出学生学号及总学分。
存储过程定义

create proc p1
as
select sno,SUM(credit) as 总学分 from sc
inner join course c on c.cno = sc.cno
group by sno

存储过程执行

exec p1

运行结果
在这里插入图片描述

含输入参数的存储过程

查询学生的学号、姓名、修的课程号、课程名、课程学分,将学生所在的系作为输入参数,执行此存储过程,并分别指定一些不同的输入参数值。
存储过程定义

create proc p2
@sdept char(10)
as
select s.sno,sname,c.cno,cname,credit from student s
inner join sc on sc.sno = s.sno
inner join course c on c.cno = sc.cno
where sdept = @sdept

存储过程执行

exec p2 '计算机系'

运行结果
在这里插入图片描述

既含输入参数,又含输出参数的存储过程

查询student表指定系的男生人数,其中系为输入参数,人数用输出参数返回。
存储过程定义

create proc p3
@sdept char(10),@res int output
as
select @res=count(*) from student
where sdept = @sdept and ssex = '男'

存储过程执行

declare @res int
exec p3 '计算机系',@res output
print @res

运行结果
在这里插入图片描述

删除存储过程

使用以下语句可以删除存储过程

drop proc p1
drop proc p2
drop proc p3

猜你喜欢

转载自blog.csdn.net/weixin_43699716/article/details/106877741
今日推荐