SQL Server编程(03)自定义存储过程

存储过程是一组预编译的SQL语句,它可以包含数据操纵语句、变量、逻辑控制语句等。

存储过程允许带参数:

  • 输入参数:可以在调用时向存储过程传递参数,此类参数可用来向存储过程中传入值(可以有默认值)
  • 输出参数:从存储过程中返回(输出)值,后面跟随OUTPUT关键字

存储过程的优点:

  1. 执行速度快
  2. 允许模块化设计
  3. 提高系统安全性
  4. 减少网络流量

创建存储过程

我们可以使用create procedure命令创建存储过程。

create procedure calcAge (
    @birthday datetime,    --输入参数
    @age int output        --输出参数,参数后面加 output
)
as
begin    --begin...end 语句块不是必须的(即使是多条语句)
    declare @now datetime
    set @now=getdate()
    set @age=YEAR(@now)-YEAR(@birthday)    --为输出参数赋值,不需要return
end

输入参数带默认值:

create procedure calcAge (
    @birthday datetime = '2012-1-1',    --输入参数,带默认值,调用的时候可以不指定
    @age int output        --输出参数,参数后面加 output
)
as
begin    --begin...end 语句块不是必须的(即使是多条语句)
    declare @now datetime
    set @now=getdate()
    set @age=YEAR(@now)-YEAR(@birthday)    --为输出参数赋值,不需要return
end

 

调用存储过程

我们新定义的存储过程有输出参数,调用的时候也需要指定参数为output

declare @age int
execute calcAge '2012-1-1', @age output        --标记参数@age为output
print @age

调用存储过程时,默认情况下指定的参数是按照定义的数序指定的,我们也可以显示的指定:

declare @myAge int
execute calcAge @age=@myAge output        --显示指定参数@age
print @myAge

 

修改存储过程

使用alter procedure命令修改存储过程,例如下面的伪代码:

alter procedure calcAge (
    @birthday datetime,
    @age int output
)
as
begin
    -- 这里是你的逻辑
end

 

删除存储过程

使用drop procedure命令删除存储过程:

drop procedure calcAge

 

posted @ 2015-10-28 14:48  拓荒者FF  阅读(3049)  评论(0编辑  收藏  举报