介绍 (Introduction)

In a previous article, Functions vs stored procedures in SQL Server, we compared Functions vs stored procedures across various attributes. In this article, we will continue the discussion. We will talk also about Table-valued functions and compare performance with stored procedures with table valued functions and scalar functions.

在上一篇文章SQL Server中的功能与存储过程中 ,我们比较了各种属性中的功能与存储过程。 在本文中,我们将继续讨论。 我们还将讨论表值函数,并比较具有表值函数和标量函数的存储过程的性能。

We will include the following topics:

我们将包括以下主题:

  1. Manipulating stored procedure results and Table valued functions 处理存储过程结果和表值函数
  2. Comparing performance of stored procedures and Table valued functions with a where clause 使用where子句比较存储过程和表值函数的性能
  3. Are the scalar functions the devil’s sons? 标量功能是魔鬼的儿子吗?

入门 (Getting started)

1.处理存储过程结果和表值函数 (1. Manipulating stored procedure results and Table valued functions)

To store data retrieved from a stored procedure in a table when we invoke it, it is necessary to create the table first and then insert the data from the stored procedure to the table.

若要在调用表时将从存储过程中检索到的数据存储在表中,有必要先创建表,然后将数据从存储过程插入表中。

Let’s take a look to an example. First, we will create a stored procedure that returns a select statement:

让我们来看一个例子。 首先,我们将创建一个存储过程,该存储过程返回一个select语句:


create procedure tablexample
as
select
[AddressID],
[AddressLine1],
[AddressLine2],
Cityfrom
[Person].[Address]

This is a procedure named tableexample and it returns select information of the table Person.Address included in the Adventureworks databases mentioned in the requirements.

这是一个名为tableexample的过程,它返回需求中提到的Adventureworks数据库中包含的表Person.Address的选择信息。

After creating the stored procedure, you need to create a table where you will store the data:

创建存储过程之后,您需要创建一个表,您将在其中存储数据:


CREATE TABLE [Person].[Address2]([AddressID] [int] NOT NULL,[AddressLine1] [nvarchar](60) NOT NULL,[AddressLine2] [nvarchar](60) NULL,[City] [nvarchar](30) NOT NULLCONSTRAINT [PK_Address_AddressID2] PRIMARY KEY CLUSTERED
([AddressID] ASC
)
) ON [PRIMARY] GO

Finally, you can do an insert into table and invoke the stored procedure:

最后,您可以在表中插入并调用存储过程:


insert into Person.Address2
exec tablexample

As you can see, it is possible to invoke a stored procedure and retrieve the data using insert into.

如您所见,可以调用存储过程并使用insert into检索数据。

If we try to do an insert into from a stored procedure to create automatically the table we will have the following result:

如果我们尝试从存储过程中进行插入以自动创建表,则会得到以下结果:


exec tablexample into
Person.Address3

When we try to insert into a table the result of the stored procedure invocation, we have the following message:

当我们尝试将存储过程调用的结果插入表中时,我们收到以下消息:

Msg 156, Level 15, State 1, Line 170
Incorrect syntax near the keyword ‘into’.

讯息156,第15级,州1,行170
关键字“ into”附近的语法不正确。

Let’s create a table valued function and compare it with the stored procedure:

让我们创建一个表值函数并将其与存储过程进行比较:


CREATE FUNCTION dbo.functiontable( )
RETURNS TABLE
AS
RETURN
(
select
[AddressID],
[AddressLine1],
[AddressLine2],
Cityfrom
[Person].[Address] )

This function named functiontable returns the information from a Person.Address table. To invoke a table valued function, we can do a select like this:

此名为functiontable的函数从Person.Address表返回信息。 要调用表值函数,我们可以执行如下选择:


select *from dbo.functiontable()

The table valued function can be used like a view. You can filters the columns that you want to see:

表值函数可以像视图一样使用。 您可以过滤要查看的列:


select AddressIDfrom dbo.functiontable()

You can also add filters:

您还可以添加过滤器:


select AddressID from dbo.functiontable()where AddressID=502

If you want to store the functions results, you do not need to create a table. You can use the select into clause to store the results in a new table:

如果要存储函数结果,则无需创建表。 您可以使用select into子句将结果存储在新表中:


select * into mytablefrom dbo.functiontable()

As you can see, you do not need to create a table as we did with the stored procedures. If you go to the Object Explorer in SSMS, you will be able to see that the table mytable was created successfully:

如您所见,您不需要像存储过程那样创建表。 如果转到SSMS中的“对象资源管理器”,将可以看到表mytable已成功创建:

2.使用where子句比较存储过程和表值函数的性能 (2. Comparing performance of stored procedures and Table valued functions with a where clause)

Some developers claim that stored procedures are faster than Table valued functions. Is that true?

一些开发人员声称存储过程比表值函数快。 真的吗?

We will create a table with a million rows for this test:

我们将为此测试创建一个包含一百万行的表:


with randowvaluesas(select 1 id, CAST(RAND(CHECKSUM(NEWID()))*100 as int) randomnumberunion  allselect id + 1, CAST(RAND(CHECKSUM(NEWID()))*100 as int)  randomnumberfrom randowvalueswhere id < 1000000)select *into mylargetablefrom randowvaluesOPTION(MAXRECURSION 0)

The code creates a table named mylargetable with a million rows with values from 1 to 100.

该代码创建一个名为mylargetable的表,该表包含一百万行,其值从1到100。

We will create a function that returns the values according to a filter specified by a parameter:

我们将创建一个函数,该函数根据参数指定的过滤器返回值:


CREATE FUNCTION dbo.functionlargetable(@rand int)
RETURNS TABLE
AS
RETURN
(
select randomnumber
from mylargetable
where randomnumber=@rand)

This function named functionlargetable will show randomnumbers equal to the parameter specified.

名为functionlargetable的函数将显示等于指定参数的随机数。

Before running the query, enable the Actual Execution option in SSMS:

在运行查询之前,请在SSMS中启用“实际执行”选项:

The following query will show random numbers equal to 59:

以下查询将显示等于59的随机数:


select randomnumber from dbo.functionlargetable(59)

The Actual Execution plan will show how the query was executed (which indexes were used, cost of the sentences, etc.):

实际执行计划将显示查询的执行方式(使用了哪些索引,句子的成本等):

We will compare the execution plan of the function to a stored procedure:

我们将把函数的执行计划与存储过程进行比较:


CREATE PROCEDURE storedwithlargetable
@rand int
as
select randomnumber
from mylargetable
where randomnumber=@rand

The procedure is showing the random numbers equal to a parameter.

该过程将显示等于参数的随机数。

We will invoke the stored procedure:

我们将调用存储过程:


exec storedwithlargetable 61

If we check the actual plan, we will have the following:

如果我们检查实际计划,我们将获得以下内容:

As you can see, the execution plan is the same. However, it is always a good practice to check the execution time.

如您所见,执行计划是相同的。 但是,检查执行时间始终是一个好习惯。

To check more detailed information about execution time run these sentences:

要查看有关执行时间的更多详细信息,请运行以下语句:


SET STATISTICS io ON
SET STATISTICS time ON
GO

We run the functions and stored procedure cleaning the buffer using these sentences:

我们使用以下语句运行函数和存储过程以清理缓冲区:


DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS;
SET NOCOUNT ON

Here you have the table of results of the function invocation time:

这里有函数调用时间的结果表:

CPU Parse time (ms) Elapsed Parse time (ms) Execution CPU time (ms) Execution (ms) Total (ms)
16 90 313 1325 1744
16 43 390 1053 1502
0 47 328 1884 2259
0 133 344 1814 2291
0 273 391 1500 2164
Average: 1992
CPU解析时间(毫秒) 解析时间(毫秒) 执行CPU时间(毫秒) 执行时间(毫秒) 总计(毫秒)
16 90 313 1325 1744
16 43 390 1053 1502
0 47 328 1884年 2259
0 133 344 1814年 2291
0 273 391 1500 2164
平均:1992

In addition, here you have the execution time of the stored procedure:

另外,这里您具有存储过程的执行时间:

CPU Parse time (ms) Elapsed Parse time (ms) Execution CPU time (ms) Execution (ms) Total (ms)
0 143 1300 1818 3261
1 0 250 1481 1731
0 0 328 1231 1559
0 0 328 1542 1870
16 276 313 1525 2130
Average: 2110
CPU解析时间(毫秒) 解析时间(毫秒) 执行CPU时间(毫秒) 执行时间(毫秒) 总计(毫秒)
0 143 1300 1818年 3261
1个 0 250 1481 1731
0 0 328 1231 1559
0 0 328 1542 1870年
16 276 313 1525 2130
平均:2110

As you can see, the average time is 1992 ms for the function and 2110 ms for the stored procedures. The performance is almost the same. So, it is safe to use Table-valued UDFs in this case.

如您所见,该函数的平均时间为1992毫秒,存储过程的平均时间为2110毫秒。 性能几乎相同。 因此,在这种情况下使用表值UDF是安全的。

3.标量函数是否有害? (3. Are the scalar functions evil?)

Some say scalar functions are the spawn of the devil

SQL Server中的功能和存储过程比较相关推荐

  1. SQL Server中的功能与存储过程

    介绍 (Introduction) Usually DBAs prefer stored procedures in SQL instead of functions in SQL Server. I ...

  2. SQL Server中的T-SQL元数据功能的完整指南

    In this article, we will demonstrate T-SQL metadata functions available in the SQL Server. 在本文中,我们将演 ...

  3. 使用DBATools PowerShell修复SQL Server中的孤立用户

    This article gives an overview of Orphan users and fixing them using DBATools PowerShell. 本文概述了Orpha ...

  4. 在SQL SERVER中实现Split功能的函数,并在存储过程中使用

    CREATE FUNCTION dbo.SplitString (@Expression NVARCHAR(4000), --要拆分的字符串          @Delimiter NVARCHAR( ...

  5. 通过 Visual Studio 对 SQL Server 中的存储过程设置断点并进入存储过程对其进行调试...

    通过 Visual Studio 的 Professional 和 Team System 版本,我们可以对 SQL Server 中的存储过程设置断点并进入存储过程对其进行调试,这样我们可以象调试应 ...

  6. SQL Server 2014新功能 -- 内存中OLTP(In-Memory OLTP)

    概述 内存中OLTP(项目"Hekaton")是一个全新的.完全集成到SQL Server的数据库引擎组件. 对OLTP工作负载访问中在内存中的数据进行了优化.内存中OLTP能够帮 ...

  7. SQL Server中的身份功能教程

    This article explores the Identity function in SQL Server with examples and differences between thes ...

  8. SQL Server中的部分存储过程

    介绍 (Introduction) SQL is an old language - almost 50 years! The first commercially-available version ...

  9. 在SQL server中如何定时自动执行存储过程

    在SQL server中如何定时自动执行存储过程 1.首先开启sql代理服务 2.打开sqlserver软件 3.拉开SQL Server 服务菜单 4.右键作业,点击新增作业 5.在一般中添加名称和 ...

最新文章

  1. OpenGL HDR高动态光照渲染的实例
  2. thinkphp json_原创干货 | Thinkphp序列化合总
  3. 图片夹_各种变调夹的优缺点、原理和使用方法
  4. ajax和fetch哪个好,axios和ajax,fetch的区别
  5. 9种对抗电脑辐射的方法
  6. 【计算几何】【分类讨论】Gym - 101243I - Land Division
  7. 利用Oracle Enterprise Manager Cloud Control 12c创建DataGuard Standby
  8. 上采样卷积转置的deconvolution方法实现双线性插值,代码实现,结果不一样
  9. pycharm 输入法光标跟随
  10. bash 单引号 双引号_Bash Shell中的单引号和双引号有什么区别?
  11. MATLAB:DTFT、DFT 相关题目学习
  12. Sat Sep 25 07:38:46 Local time zone must be set--see zic manual page 2021
  13. Psim仿真_pi输出加限幅(疑惑)
  14. bmp180气压传感器工作原理_【科普】40种传感器工作原理
  15. Mencoder转换视频
  16. 企业物联网平台如何选择?
  17. 辐射发射的测试标准和测试方法
  18. flash高科技php网站源码下载,Flash小游戏PHP源码
  19. 视频点播系统搭建有哪些可选方案?
  20. 计算机桌面有一条红线去不掉,电脑屏幕中间有一条红线,请问怎么除去?

热门文章

  1. 数据结构与算法系列——排序(10)_归并排序
  2. 对于SQL注入的理解
  3. linux下的mongodb数据库原生操作
  4. python正则表达式之re模块方法介绍
  5. 01Python基础_08模块和包
  6. logstash_output_mongodb插件用途及安装详解
  7. 第四周作业 简单地邮件发送实现
  8. hdu 2035 人见人爱A^B (快速幂)
  9. promise实现红绿灯
  10. 牛客网模拟笔试——庆祝61(JavaScript)