T-Sql(三)存储过程(Procedure)

  今天讲下T-sql语法中存储过程的用法,我们一开始学习数据库语言的时候就是用一些简单的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关键字。

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

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

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

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

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

  下面我做了一个小示例

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

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;

  执行存储过程:

execute proc_SelectProductsWithPriceRange 17,null

  其实这些代码都是大学时候学习的时候整理的,现在写这些算是去复习一下,也想去帮助那些刚刚踏入编程行业的学子们(大牛们请飘过),我想在年前把这两年整理的一些编程知识系统的整理下来,当然都是一些简单的,并附一些示例,希望帮助初学者去理解,还希望大家关注一下。。。

原文地址:https://www.cnblogs.com/xishuai/p/3372754.html