In this article, we will learn how to create stored procedures in SQL Server with different examples.

在本文中,我们将通过不同的示例学习如何在SQL Server中创建存储过程。

SQL Server stored procedure is a batch of statements grouped as a logical unit and stored in the database. The stored procedure accepts the parameters and executes the T-SQL statements in the procedure, returns the result set if any.

SQL Server存储过程是一组作为逻辑单元分组并存储在数据库中的语句。 存储过程接受参数并在过程中执行T-SQL语句,并返回结果集(如果有)。

To understand differences between functions and stored procedures in SQL Server, you can refer to this article, Functions vs stored procedures in SQL Server and to learn about Partial stored procedures in SQL Server, click Partial stored procedures in SQL Server.

要了解SQL Server中的函数和存储过程之间的区别,可以参考本文SQL Server中的函数与存储过程,并了解SQL Server中的部分存储过程 ,单击SQL Server中的部分存储过程 。

使用存储过程的好处 (Benefits of using a stored procedure)

It can be easily modified: We can easily modify the code inside the stored procedure without the need to restart or deploying the application. For example, If the T-SQL queries are written in the application and if we need to change the logic, we must change the code in the application and re-deploy it. SQL Server Stored procedures eliminate such challenges by storing the code in the database. so, when we want to change the logic inside the procedure we can just do it by simple ALTER PROCEDURE statement.

可以轻松修改它 :我们可以轻松地修改存储过程中的代码,而无需重新启动或部署应用程序。 例如,如果T-SQL查询是在应用程序中编写的,并且我们需要更改逻辑,则必须更改应用程序中的代码并重新部署它。 SQL Server存储过程通过将代码存储在数据库中消除了此类挑战。 因此,当我们想要更改过程内部的逻辑时,只需执行简单的ALTER PROCEDURE语句即可。

Reduced network traffic: When we use stored procedures instead of writing T-SQL queries at the application level, only the procedure name is passed over the network instead of the whole T-SQL code.

减少网络流量:当我们使用存储过程而不是在应用程序级别编写T-SQL查询时,只有过程名称通过网络传递,而不是整个T-SQL代码传递。

Reusable: Stored procedures can be executed by multiple users or multiple client applications without the need of writing the code again.

可重用:存储过程可以由多个用户或多个客户端应用程序执行,而无需再次编写代码。

Security: Stored procedures reduce the threat by eliminating direct access to the tables. we can also encrypt the stored procedures while creating them so that source code inside the stored procedure is not visible. Use third-party tools like ApexSQL Decrypt to decrypt the encrypted stored procedures.

安全性:存储过程通过消除对表的直接访问来减少威胁。 我们还可以在创建存储过程时对其进行加密,以使存储过程中的源代码不可见。 使用ApexSQL Decrypt等第三方工具解密加密的存储过程。

Performance: The SQL Server stored procedure when executed for the first time creates a plan and stores it in the buffer pool so that the plan can be reused when it executes next time.

性能:首次执行时,SQL Server存储过程将创建一个计划并将其存储在缓冲池中,以便下次执行该计划时可以重用该计划。

I am creating sample tables that will be used in the examples in this article.

我正在创建示例表,将在本文的示例中使用。

CREATE TABLE Product
(ProductID INT, ProductName VARCHAR(100) )
GOCREATE TABLE ProductDescription
(ProductID INT, ProductDescription VARCHAR(800) )
GOINSERT INTO Product VALUES (680,'HL Road Frame - Black, 58')
,(706,'HL Road Frame - Red, 58')
,(707,'Sport-100 Helmet, Red')
GOINSERT INTO ProductDescription VALUES (680,'Replacement mountain wheel for entry-level rider.')
,(706,'Sturdy alloy features a quick-release hub.')
,(707,'Aerodynamic rims for smooth riding.')
GO

创建一个简单的存储过程 (Creating a simple stored procedure)

We will create a simple stored procedure that joins two tables and returns the result set as shown in the following example.

我们将创建一个简单的存储过程,该过程将两个表连接起来并返回结果集,如以下示例所示。

CREATE PROCEDURE GetProductDesc
AS
BEGIN
SET NOCOUNT ONSELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM
Product P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductIDEND

We can use ‘EXEC ProcedureName’ to execute stored procedures. When we execute the procedure GetProductDesc, the result set looks like below.

我们可以使用“ EXEC ProcedureName”来执行存储过程。 当我们执行过程GetProductDesc时,结果集如下所示。

使用参数创建存储过程 (Creating a stored procedure with parameters)

Let us create a SQL Server stored procedure that accepts the input parameters and processes the records based on the input parameter.

让我们创建一个SQL Server存储过程,该存储过程接受输入参数并根据输入参数处理记录。

Following is the example of a stored procedure that accepts the parameter.

以下是接受参数的存储过程的示例。

CREATE PROCEDURE GetProductDesc_withparameters
(@PID INT)
AS
BEGIN
SET NOCOUNT ONSELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM
Product P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID
WHERE P.ProductID=@PIDEND
EXEC GetProductDesc_withparameters 706

While executing the stored procedure we need to pass the input parameter. Please refer to the below image for the result set.

在执行存储过程时,我们需要传递输入参数。 请参阅下图获取结果集。

使用默认参数值创建存储过程 (Creating a stored procedure with default parameters values)

Following is the example of a stored procedure with default parameter values.

以下是带有默认参数值的存储过程的示例。

CREATE PROCEDURE GetProductDesc_withDefaultparameters
(@PID INT =706)
AS
BEGIN
SET NOCOUNT ONSELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM
Product P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID
WHERE P.ProductID=@PIDEND

When we execute the above procedure without passing the parameter value, the default value 706 will be used. But when executed passing the value, the default value will be ignored and the passed value will be considered as a parameter.

当我们执行上述过程而没有传递参数值时,将使用默认值706。 但是当执行传递值时,默认值将被忽略,传递的值将被视为参数。

使用输出参数创建存储过程 (Creating a stored procedure with an output parameter)

Below is the example of a stored procedure with an output parameter. The following example retrieves the EmpID which is an auto identity column when a new employee is inserted.

下面是带有输出参数的存储过程的示例。 下面的示例检索EmpID,它是插入新员工时的自动标识列。

CREATE TABLE Employee (EmpID int identity(1,1),EmpName varchar(500))
CREATE PROCEDURE ins_NewEmp_with_outputparamaters
(@Ename varchar(50),
@EId int output)
AS
BEGIN
SET NOCOUNT ONINSERT INTO Employee (EmpName) VALUES (@Ename)SELECT @EId= SCOPE_IDENTITY()END

Executing the stored procedures with output parameters is bit different. We must declare the variable to store the value returned by the output parameter.

使用输出参数执行存储过程有些不同。 我们必须声明变量以存储输出参数返回的值。

declare @EmpID INTEXEC ins_NewEmp_with_outputparamaters 'Andrew', @EmpID OUTPUTSELECT @EmpID

创建一个加密的存储过程 (Creating an encrypted stored procedure)

We can hide the source code in the stored procedure by creating the procedure with the “ENCRYPTION” option.

通过使用“ ENCRYPTION”选项创建过程,我们可以在存储过程中隐藏源代码。

Following is the example of an encrypted stored procedure.

以下是加密存储过程的示例。

CREATE PROCEDURE GetEmployees
WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON SELECT EmpID,EmpName from Employee
END

When we try to view the code of the SQL Server stored procedure using sp_helptext, it returns “The text for object ‘GetEmployees’ is encrypted.”

当我们尝试使用sp_helptext查看SQL Server存储过程的代码时,它返回“对象'GetEmployees'的文本已加密。”

When you try to script the encrypted stored procedure from SQL Server management studio, it throws an error as below.

当您尝试从SQL Server Management Studio编写加密存储过程的脚本时,它将引发如下错误。

创建一个临时程序 (Creating a temporary procedure)

Like the temporary table, we can create temporary procedures as well. There are two types of temporary procedures, one is a local temporary stored procedure and another one is a global temporary procedure.

像临时表一样,我们也可以创建临时过程。 临时过程有两种类型,一种是本地临时存储过程,另一种是全局临时过程。

These procedures are created in the tempdb database.

这些过程在tempdb数据库中创建。

Local temporary SQL Server stored procedures: These are created with # as prefix and can be accessed only in the session where it created. This procedure is automatically dropped when the connection is closed.

本地临时SQL Server存储过程 :这些存储过程以#作为前缀创建,并且只能在其创建的会话中访问。 关闭连接后,此过程将自动删除。

Following is the example of creating a local temporary procedure.

以下是创建本地临时过程的示例。

CREATE PROCEDURE #Temp
AS
BEGIN
PRINT 'Local temp procedure'
END

Global temporary SQL Server stored procedure: These procedures are created with ## as prefix and can be accessed on the other sessions as well. This procedure is automatically dropped when the connection which is used to create the procedure is closed.

全局临时SQL Server存储过程:这些过程以##作为前缀创建,也可以在其他会话上访问。 当用于创建过程的连接关闭时,该过程将自动删除。

Below is the example of creating a global temporary procedure.

下面是创建全局临时过程的示例。

CREATE PROCEDURE ##TEMP
AS
BEGIN
PRINT 'Global temp procedure'
END

修改存储过程 (Modifying the stored procedure)

Use the ALTER PROCEDURE statement to modify the existing stored procedure. Following is the example of modifying the existing procedure.

使用ALTER PROCEDURE语句修改现有的存储过程。 以下是修改现有过程的示例。

ALTER PROCEDURE GetProductDesc
AS
BEGIN
SET NOCOUNT ONSELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM
Product P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductIDEND

重命名存储过程 (Renaming the stored procedure)

To rename a stored procedure using T-SQL, use system stored procedure sp_rename. Following is the example that renames the procedure “GetProductDesc” to a new name “GetProductDesc_new”.

要使用T-SQL重命名存储过程,请使用系统存储过程sp_rename。 以下是将过程“ GetProductDesc”重命名为新名称“ GetProductDesc_new”的示例。

sp_rename 'GetProductDesc','GetProductDesc_new'

结论 (Conclusion)

In this article, we explored SQL Server stored procedures with different examples. In case you have any questions, please feel free to ask in the comment section below.

在本文中,我们通过不同的示例探索了SQL Server存储过程。 如果您有任何疑问,请随时在下面的评论部分中提问。

翻译自: https://www.sqlshack.com/sql-server-stored-procedures-for-beginners/

SQL Server存储过程初学者相关推荐

  1. SQL Server存储过程输入参数使用表值

    在2008之前如果我们想要将表作为输入参数传递给SQL Server存储过程使比较困难的,可能需要很多的逻辑处理将这些表数据作为字符串或者XML传入. 在2008中提供了表值参数.使用表值参数,可以不 ...

  2. SQL Server存储过程里全库查找引用的数据库对象(表、存储过程等)

    SQL Server存储过程全库匹配数据库对象(表.存储过程等) 简介 可以通过自定义存储过程sp_eachdb来遍历每个数据库然后结合sys.objects 关联sys.sql_modules后的d ...

  3. SQL server 存储过程的建立和调用

    SQL server 存储过程的建立和调用 存储过程的建立和调用 --1.1准备测试需要的数据库:test,数据表:物料表,采购表 if not exists (select * from maste ...

  4. java调用存储过程 sql server_Java中调用SQL Server存储过程示例

    Java中调用SQL Server存储过程示例2007-09-03 08:48来源:论坛整理作者:孟子E章责任编辑:方舟·yesky评论(3) 最近做了个Java的小项目(第一次写Java的项目哦), ...

  5. Microsoft SQL Server 存储过程

    Microsoft SQL Server 存储过程 TRIGGER DDL触发器:主要用于防止对数据库架构.视图.表.存储过程等进行的某些修改:DDL事件是指对数据库CREATE,ALTER,DROP ...

  6. db2 删除存储过程_数据库教程-SQL Server存储过程使用及异常处理

    SQL Server存储过程 存储过程(Procedure)是数据库重要对象之一,也是数据库学习的重点之一.本文,我们以SQL Server为例对存储过程的概念.定义.调用.删除及存储过程调用异常等通 ...

  7. SQL Server存储过程中使用表值作为输入参数示例

    这篇文章主要介绍了SQL Server存储过程中使用表值作为输入参数示例,使用表值参数,可以不必创建临时表或许多参数,即可向 Transact-SQL 语句或例程(如存储过程或函数)发送多行数据,这样 ...

  8. oracle如何调试sql,调试oracle与调试sql server存储过程

    [IT168 技术]关于存储过程的调试,知道方法以后很简单,但在不知道的时候,为了测试一个存储过程的正性,print,插入临时表等可谓是使出了浑身解数,烦不胜烦.下面就把我工作中调试oracle存储过 ...

  9. SQL Server 存储过程中使用raiserror抛出异常

    转自(SQL Server 存储过程中使用raiserror抛出异常 ) 一 系统预定义错误代码 SQL Server 有3831个预定义错误代码,由master.dbo.sysmessages 表维 ...

最新文章

  1. 0x66.图论 - Tarjan算法与无向图连通性
  2. 英特尔反驳质疑:芯片供应充足、10nm量产没问题
  3. 趣谈网络协议笔记-二(第十六讲上)
  4. Android - N级树形结构实现
  5. MIT开源高性能自动微分框架Enzyme:速度提升4.5倍
  6. 算法题目——被围绕的区域(dfs,bfs)
  7. EditPlus连接远程Linux虚拟机
  8. php成品代码,PHP代码
  9. 口罩日产量破1亿背后:近3000家企业疯狂增产转产
  10. java indexof 参数_Java indexOf() 方法
  11. PySide使用QVariant
  12. 如果你想学好Py thon,我这里有几本电子书想送你
  13. 用博客记录成长的历程
  14. 《德鲁克管理思想精要》读书笔记2 - 企业的宗旨、目标
  15. 插入移动硬盘时出现Synaptics.exe - 损坏的映像错误的解决办法
  16. DLNA,DMS介绍
  17. 新开淘宝店铺如何推广运营
  18. Vue开发项目入门——Vue脚手架
  19. 免费css布局和模板集合
  20. Content(内容)

热门文章

  1. python写一个数据库的界面_Python GUI教程(十四):在PyQt5中使用数据库
  2. 转:Java中的异常处理
  3. 移动端键盘弹起导致底部按钮上浮解决方案
  4. java配置环境及安装
  5. 使用 python 处理 nc 数据
  6. Java基础知识强化23:Java中数据类型转换(面试题)
  7. 关于静态编译出现的问题以及解决方法
  8. UVA 10564 - Paths through the Hourglass (dp)
  9. 微信公众平台消息接口开发(27)彩票查询
  10. jQuery Tips(5)----关于伪类选择符