【SqlServer】SqlServer存储过程使用

时间:2023-03-09 04:06:12
【SqlServer】SqlServer存储过程使用

我们一开始学习数据库语言的时候就是用一些简单的insert,select等语法,但是随着我们学习数据库的深入,就会发现一些简单的语法满足不了我们的要求,比如处理一些业务逻辑,多表关联的时候,还有就是虽然程序或是简单的sql语句也会实现其效果,但是性能或是效率会很低。

  这时候我们就会用到T-sql中的存储过程,存储过程就像C#中的方法一样,传递参数,执行一些操作,返回相应的值。

  我们用SQLSERVER2008自带的AdventureWorks示例数据库来讲解。

  首先我们新建一个存储过程,关键字为Procedure,示例代码: 

create procedure proc_Sales_SalesReason
as
begin
select * from Sales.SalesReason;
end

  我们新建的一个proc_Sales_SalesReason存储过程,执行查询操作,一般存储过程命名为proc_+名称,这样有利于识别。

  执行存储过程示例代码:

execute proc_Sales_SalesReason

drop procedure  proc_Sales_SalesReason    --删除存储过程

  修改存储过程的话用alter关键字。

  以上只是简单的存储过程,就想无参数的方法一样,下面是带参数的示例代码:

【SqlServer】SqlServer存储过程使用
create procedure proc_Sales_SalesReason
(@SalesReasonID int,
@Name nvarchar(50),
@ReasonType nvarchar(50),
@ModifiedDate datetime)
as
begin
insert into Sales.SalesReason(SalesReasonID, Name, ReasonType, ModifiedDate)
values(@SalesReasonID, @Name, @ReasonType, @ModifiedDate);
end
【SqlServer】SqlServer存储过程使用

  这是一个执行插入数据的存储过程,执行示例代码:

execute proc_Sales_SalesReason 100,'text1','as','2011-12-12';

  以上讲解的都是一些简单存储过程的用法,在这里只是起到抛砖引玉的作用,大家可以有时间好好研究下,去处理一些复杂的业务逻辑。

  下面我做了一个小示例

  select :按价格范围来查询
  要求:如果两个参数均存在,则表示查询该指定范围的内容;
  若均不存在,则查询所有
  若@PriceFrom参数存在,则,查询>=@PriceFrom
  @priceTo存在,则<=@priceTo

【SqlServer】SqlServer存储过程使用
create procedure proc_SelectProductsWithPriceRange
(
@PriceFrom money,
@priceTo money
)
as
begin
if @PriceFrom is not null
begin
if @priceTo is not null
begin
select *from dbo.Products
where Price between @PriceFrom and @priceTo;
end
else
begin
select *from dbo.Products
where Price>=@PriceFrom;
end
end;
else
begin
if @priceTo is not null
begin
select *from dbo.Products
where Price<=@priceTo;
end
else
begin
select *from dbo.Products
end
end
end;
【SqlServer】SqlServer存储过程使用

  执行存储过程:

execute proc_SelectProductsWithPriceRange 17,null

  

原文链接:T-sql 存储过程