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
    ```
相关推荐
李广坤8 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
Scout-leaf9 小时前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户2986985301412 小时前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
爱可生开源社区1 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1772 天前
《从零搭建NestJS项目》
数据库·typescript
mudtools2 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的2 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21882 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi2 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql