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
    
  • 相关阅读:
    我告诉你 电脑软件工具
    mysql 查询当天、本周,本月,上一个月的数据
    springboot:springboot+mybatis多数据源最简解决方案
    MySQL数据库优化的(经典必看)
    MyBatis 的强大特性之一便是它的动态 SQL之常用属性使用
    你知道Spring 中使用了哪些设计模式?
    kafka 相关面试问题
    掌握TCP/IP的通信原理(三次握手、四次挥手)。
    jsp和servlet实现文件的上传和下载
    Java获取数据库记录通过javabean映射,并存入list集合
  • 原文地址:https://www.cnblogs.com/youring2/p/4917333.html
Copyright © 2011-2022 走看看