sql存储过程

本文详细介绍了SQL Server中的存储过程概念,包括其定义、创建、执行、修改及编译的方法,并通过具体实例展示了如何使用带参数及返回参数的存储过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值