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
  • 相关阅读:
    java PKCS7Padding 加密Cannot find any provider supporting AES/CBC/PKCS7Padding 解决办法
    win7系统c盘瘦身,去虚拟内存方式
    跟据经纬度实现附近搜索Java实现
    Java 406
    window.showModalDialog 子窗口和父窗口不兼容最新的谷歌
    <html:text> Id属性
    Unity3D GUI学习之GUI窗口的使用
    Unity3D GUI学习之GUILayout控件及使用
    Unity3D GUI之自定义风格组件
    Unity3D GUI学习
  • 原文地址:https://www.cnblogs.com/sqxie/p/6648144.html
Copyright © 2011-2022 走看看