概念:SQL Server提供了一种方法,它可以将一些固定的操作集中起来由SQL Server数据库服务器来完成,以实现某个任务,这种方法就是存储过程。
存储过程是SQL语句和可选控制流语句的预编译集合,存储过程在数据库中可由应用程序通过一个调用执行,而且允许用户申明变量、有条件的执行以及其它强大的编程功能
(1)实例:
if exists (select name from sysobjects where name='studentinfo' and type='P ')
drop procedure studentinfo--删除存储过程
go
create procedure studentinfo--创建存储过程
as
select * from student
go
execute studentinfo --执行存储过程
(2)例二:带参数的存储过程
use NorthWind
go
create procedure insert_Products_1(--创建一存储过程
@SupplierID_2 int ,--参数
@CategoryID_3 int ,
@ProductName_1 nvarchar
)
as insert into products
(ProductName,SupplierID,CategoryID)
values
(@ProductName_1,@SupplierID_2,@CategoryID_3)
go
exec insert_Products_1 2,2,2--执行存储过程并传入参数
select * from products where SupplierID=2 and CategoryID=2
(3)例三:使用返回参数
create procedure query_products
(
@SupplierID_1 int ,
@ProductName_2 nvarchar(40) output --使用返回参数
)
as
select @ProductName_2=ProductName from products
where SupplierID=@SupplierID_1
declare @product nvarchar(40)
exec query_products 7,@product output--执行存储过程query_products,这里的7是传入的参数SupplierID,@product output指ProductName
select '产品名'=@product
最后会显示:
产品名
Outback Lager
(4)查看存储过程 (通过系统表+存储过程名)
sp_helptext query_products
sp_depends query_products
sp_help query_products
修改存储过程
例:
alter proc pr_searchempl
@state char(2)
as
select * from table where state=@state
go
(5)编译存储过程
在我们使用了一次存储过程后,可能会因为某些原因,必须向表中新增加数据列或者为表新添加索引,从而改变数据库的逻辑结构,这时需要重新编译
1。在建立存储过程时设定重新编译
create procedure procedure_name
with recompile
as sql_statement
2。在执行存储过程时设定重新编译
execute procedure_name
with recompile
3。通过使用系统 存储过程设定重编译
exec sp_recompile object