定义
存储过程是一个预编译的sql语句 ,编译后可多次使用。
优势:响应时间上来说有优势,可以给我们带来运行效率提高的好处,且使用存储过程的系统更加稳定
缺点:维护性较差,相对于简单sql,存储过程并没有什么优势,并且在进行调试时比较困难
作用
可以提高运行效率,并且使用存储过程的系统更稳定。
更多的可以参考 【随风飘扬中】的 存储过程的作用和意义
使用范围
当一个业务需要操作多个表时可以使用存储过程来提升效率
怎么操作
创建无参无输出存储过程
--创建存储过程
create proc cp_books
as
--操作语句
select * from books
--调用不带参的存储过程
exec cp_books
创建有参无输出存储过程
--多个参数使用逗号隔开
create proc cp_books
(
@name nvarchar(20)
)
as
--操作语句
select * from books where name like '%'+@name+'%'
--调用带参的存储过程
--多个参数使用逗号隔开不需要小括号包裹
exec cp_books @name='aa'
创建无参有输出存储过程
--创建存储过程--
create proc cp_books
(
@mycount int output --输出参数需要output
)
as
--操作语句
select @mycount=count(*) from books
--调用有输出的存储过程
--先定义一个变量进行接收
declare @mycount int
set @mycount= exec cp_books
print @mycount
创建有参有输出存储过程
--创建存储过程--
create proc cp_books
(
@name nvarchar(20)
@mycount int output --输出参数需要output
)
as
--操作语句
select @mycount=count(*) from books
select * from books where name like '%'+@name+'%'
--调用有输出的存储过程
--先定义一个变量进行接收
declare @mycount int
set @mycount= exec cp_books
print @mycount
判断存储过程是否存在删除存储过程
-- 判断要创建的存储过程名是否存在
if exists (select * from dbo.sysobjects
where id = object_id(N'[dbo].[存储过程名]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1)
-- 删除存储过程
drop procedure [dbo].[存储过程名]