SQL第19课:存储过程

2018-08-29  本文已影响12人  周运来就是我

存储过程

存储过程是由SQL语句和控制语句构成的语句串(语句集合)。它不仅可以带有输入参数还可以带有输出参数,存储过程能够通过接收参数,向调用者返回结果集,结果集的格式由调用者确定。返回状态值给调用者,指明调用成功还是失败,包括针对数据库的操作语句,并且可以在一个存储过程中调用另一存储过程。 另外存储过程好处不必多说,比如支持sql重用、执行速度快、减少网络流量、安全可靠。

在sql server中存储过程分为两类:系统提供存储过程和用户自定义存储过程。 系统存储过程主要存储在master数据库中,并以sp_为前缀,主要是从系统表中获取信息;用户存储过程由用户创建并完成特定功能,这里我主要写的是用户存储过程

1. 创建存储过程

sql server中使用create procedure语句创建、编译存储过程。

语法如下:

create procedure procedure_name [;version number]
[{ @parameter data_type}
       [varying] [=default value][output]
] [,...n]
[with
        {recompile|encryption|recompile,encryption}]
  [for replication]
 as sql_statement [...n]

解释:

create procedure usp_select_teacher @depart char( 10),@avg_age int output,@max_age int output
as
select * from teacher
where dname= @depart
select @max_age= max(age )
from teacher
where dname= @depart
select @avg_age= avg(age )
from teacher
where dname= @depart
if @avg_age <= 30
select ' 年龄结构'= '年龄结构偏年轻', '平均年龄' =@avg_age
if @avg_age > 30 and @avg_age <=40
select ' 年龄结构'= '年龄结构合理', '平均年龄' =@avg_age
if @avg_age > 40
select ' 年龄结构'= '年龄结构偏大', '平均年龄' =@avg_age

2.调用存储过程

sql server使用execute命令调用存储过程

示例:调用存储过程usp_select_teacher,并查看其输出参数的值。

declare @avgage int ,@maxage int
execute usp_select_teacher ' 计算机', @avgage output, @maxage output

我的运行结果如下:

image

Sql Server存储过程和函数浅谈

上一篇 下一篇

猜你喜欢

热点阅读