zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    OpenShift提供的免费.net空间 数据库 申请流程图文
    javascript实现全选全取消功能
    编写一个方法来获取页面url对应key的值
    面试题目产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。
    面试宝典
    HDU 4619 Warm up 2 贪心或者二分图匹配
    HDU 4669 Mutiples on a circle 数位DP
    HDU 4666 最远曼哈顿距离
    HDU 4035 Maze 概率DP 搜索
    HDU 4089 Activation 概率DP
  • 原文地址:https://www.cnblogs.com/youring2/p/4917333.html
Copyright © 2011-2022 走看看