SQL Server—T-sql存储过程详解

存储过程

  • T-SQL 存储过程是在 SQL Server 数据库中编写的一种程序,它可以包含一系列的 T-SQL 语句,用于完成特定的数据库操作任务。存储过程在数据库中被创建,然后可以通过指定存储过程的名称并给出参数(如果该过程接受参数)来执行。

    • 1概念:

      预先存储好的sql程序,通过名称和参数进行执行,供应程序去调用,也可以有返回结果,存储过程可以包含sql语句,可以包含流程控制、逻辑语句等。

    2 系统自带存储过程

      1. 列出服务器所有数据库 exec sp_databases
      1. 列出有关指定数据库或者所有的数据库信息 exec sp_helpdb MSDB
      1. 更改数据库名字,@newname 新名字; @dbname 旧名称 exec sp_renamedb @dbname = 'AsD',@newname = 'AD'
      1. 返回某个表列的信息 exec sp_columns Students
    • 5 查询一个表的约束信息 exec sp_helpconstraint Students

      1. 查询表的所有信息 exec sp_help Students
      1. 查看某个表的索引信息 exec sp_helpindex Students

    3 自定义带参数存储过程

    • 语法:

    复制代码
    ```sql
    -- create procedure过程名
    -- @参数1 数据类型
    -- @参数2 数据类型
    -- as 
    --   sql语句
    -- go
    ```
    • 实例:

    复制代码
    ```sql
    create procedure usp_test2
    	@cs int,
    as
    	select StudentId from Students where @cs = Id
    go
    -- 调用带参数的存储过程
    exec usp_test2 1000
    ```

    4 自定义不带参数存储过程

    • 语法:

    复制代码
    ```sql
    -- create procedure过程名
    -- as 
    --   sql语句
    -- go
    ```
    • 实例:

    复制代码
    ```sql
    create procedure usp_test2
    as
    	select StudentId from Students where Id = 100000
    go
    -- 调用带参数的存储过程
    exec usp_tes
    ```

    5 自定义带输出参数存储过程

    • 语法:

    复制代码
    ```sql
    -- create procedure过程名
    -- @参数1 数据类型 output
    -- as 
    --   sql语句
    -- go
    ```
    • 实例:

    复制代码
    ```sql
    create procedure usp_tt3
    	-- 输出参数返回值
    	@jigecount int output,
    	@quekaocount int output
    as
    	select @jigecount = 23,@quekaocount=30
    go	
    
    -- 调用
    declare @a int,@b int
    exec usp_tt3  @a output,@b output
    print(convert(varchar,@a)+'i'+convert(varchar,@b)) --打印结果
    
    -- 结果:23i30
    ```

    6 自定义带默认值参数的存储过程

    • 语法:

    复制代码
    ```sql
    -- create procedure过程名
    -- @参数1 数据类型 = 默认值 output
    -- as 
    --   sql语句
    -- go
    ```
    • 实例:

    复制代码
    ```sql
    create procedure usp_test2
    	@cs int = 10 output
    as
    	select StudentId from Students where @cs = Id
    go
    -- 调用带参数的存储过程(调用时可以不带参数)
    exec usp_test2
    ```
相关推荐
hez20104 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
RestCloud11 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud11 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence13 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
mudtools18 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
DemonAvenger20 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
唐青枫21 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud1 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net