定义:
sql语句执行的时候要先编译,然后执行。存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中。用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。
优点:
允许模块化程序设计,只需创建一次存储过程,并将其存储在数据库中,以后可在程序中调用该过程任意次
执行效益高
减少网络流量
可保证数据的安全性和完整性
分类:
系统存储过程 以sp_开头并存放在master数据库中
扩展存储过程 以xp_开头
用户自定义存储过程 用户自己定义
这里重点介绍用户自定义存储过程
自定义存储过程又分为两种:带参数的存储过程及不带参数的存储过程
带参数的存储过程又分为:带输入参数的存储过程和带输出参数的存储过程
存储过程语法规则:
create proc[edure](关键字,中括号内为可选内容) procName(存储过程名字)
@参数 数据类型=默认值, (输入参数)
@参数 数据类型 output(输出参数必须加上output)
as
sql语句
go
删除存储过程
创建的存储过程位于sysobjects表中
if exists(select * from sysobjects where name='存储过程名字')
drop proc 存储过程
go
存储过程执行使用关键字exec
执行无参存储过程
exec 存储过程名
执行输入参数存储过程
如:
exec 存储过程 参数值
执行输出参数的存储过程要求定义变量用来接受存储过程的返回值
declare @count int (数据类型需和存储过程中输出参数类型一致)
exec 存储过程 输出参数 output (output不能少)
print 输出参数 (用于显示输出参数)
创建无参的存储过程
查询student表中所有记录
if exists(select * from sysobjects where name='proc_select')
drop proc proc_select
go
create proc proc_select
as
select * from student
go
执行存储过程
exec proc_select 效果类似于 select * from student
创建带输入参数的存储过程
比如根据用户名查询用户密码
if exists(select * from sysobjects where name='proc_username')
drop proc proc_username
go
create proc proc_username
@username varchar(50)
as
select pwd from userinfo where username=@username
执行存储过程:
exec proc_username admin (或@username=admin)
创建带输出参数的存储过程执行时需要自定义一个变量用来接受存储过程返回的值
比如查询userinfo表中有多少条记录
if exists(select * from sysobjects where name='proc_num')
drop proc proc_num
go
create proc proc_num
@count int output (output不能少,不能赋默认值)
as
select @count=count(*) from userinfo
go
执行存储过程
declare @n int
exec proc_num @n output (output不能少)
go
print @n 显示表中有多少条记录
注:定义参数时多个参数间用逗号隔开而不是分号最后一个参数逗号可省略