博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SQL Server内联表值函数
阅读量:2510 次
发布时间:2019-05-11

本文共 9557 字,大约阅读时间需要 31 分钟。

In this article series, we will find basics and common usage scenarios about the inline table-valued functions and we will also be consolidating your learnings with practical examples.

在本系列文章中,我们将找到有关内联表值函数的基础知识和常见用法场景,并且还将通过实际示例巩固您的学习经验。

  • Note: To learn more about multi-statement table-valued functions, please refer to the 注意:要了解有关多语句表值函数的更多信息,请参阅 article文章

At first, we will briefly look for an answer to the “Why should we use functions in the SQL Server?” question.

首先,我们将简要寻找“为什么要在SQL Server中使用函数?”的答案。 题。

In the SQL Server database development process, functions allow us to wrap up the codes in a single database executable database object. In other words, functions allow applying the encapsulation idea to T-SQL codes. So, a written function can be reused multiple times. In this way, we don’t spend time writing the same code over and over again and as a result, we can reduce the repetition of code. Additionally, the SQL Server function usage helps to degrade the code clutter.

在SQL Server数据库开发过程中,函数使我们可以将代码包装在单个数据库可执行数据库对象中。 换句话说,函数允许将封装思想应用于T-SQL代码。 因此,编写的函数可以多次重用。 这样,我们就不必花时间一遍又一遍地编写相同的代码,因此,我们可以减少代码的重复。 此外,SQL Server函数的用法有助于降低代码混乱度。

描述 ( Description )

The simple definition of the table-valued function (TVF) can be made such like that; a user-defined function that returns a table data type and also it can accept parameters. TVFs can be used after the FROM clause in the SELECT statements so that we can use them just like a table in the queries.The first thing that comes to our mind is that, what is the main difference between the view (Views are virtual database objects that retrieve data from one or more tables) and TVF? The views do not allow parameterized usage this is the essential difference between views and TVFs. In the following sections, we will reinforce these theoretical pieces of information with practical examples from easy to the difficult. The TVFs can be categorized into two types. These are inline and multi-statement table-valued functions. In this article, we particularly focus on the inline one.

可以像这样对表值函数TVF )进行简单定义; 用户定义的函数,它返回表数据类型,并且可以接受参数。 TVFs后可以在FROM子句中的SELECT语句,这样我们就可以使用它们就像是涉及到我们的脑海中查询。第一个事情表是被使用有什么看法之间的主要区别( 视图是虚拟数据库对象从一个或多个表中检索数据)TVF 视图不允许参数化使用,这是视图和TVF之间的本质区别。 在以下各节中,我们将通过从易到难的实际示例来加强这些理论信息。 TVF可以分为两种类型。 这些是内联多语句 表值函数 。 在本文中,我们特别关注内联代码。

You can direct to this article, , to gain knowledge about built-in functions and user-defined scalar functions in SQL Server.

您可以直接参考本文 ,以获取有关知识。

Note: All the examples of this article will be used on the sample database and queries formatted in the .

注意:本文的 所有示例都将在 示例数据库中 使用, 并以 查询

创建内联表值函数(iTVF) ( Creating an inline table-valued function (iTVF))

The iTVF has not included BEGIN/END block in their syntax and the SELECT statement is the output of this type of functions and this is the finest detail of the iTVF.

iTVF的语法中未包含BEGIN / END块,而SELECT语句是此类函数的输出,这是iTVF的最佳细节。

The following T-SQL statement creates a very basic iTVF and the output of this function will be the Product table.

下面的T-SQL语句创建一个非常基本的iTVF ,此功能的输出将是Product表。

CREATE FUNCTION [dbo].[udfGetProductList](@SafetyStockLevel SMALLINT)RETURNS TABLEASRETURN(SELECT Product.ProductID,         Product.Name,         Product.ProductNumber FROM Production.Product WHERE SafetyStockLevel >= @SafetyStockLevel)

Now, we will tackle the code line by line.

现在,我们将逐行处理代码。

CREATE Function udfGetProductList(@SafetyStockLevel SMALLINT)

The above code part specifies the name of the function and parameters name and data types of the function. Particularly, for our function, we specify only one parameter which is named @SafetyStockLevel and its data type is SMALLINT.

上面的代码部分指定了函数的名称以及函数的参数名称和数据类型。 特别是,对于我们的函数,我们仅指定一个名为@SafetyStockLevel的参数,其数据类型为SMALLINT

RETURNS TABLE

The above code part specifies that the function will return a table.

上面的代码部分指定该函数将返回一个表。

RETURN(SELECT Product.ProductID,         Product.Name,         Product.ProductNumber FROM Production.Product WHERE SafetyStockLevel >= @SafetyStockLevel)

The above code part returns data like ProductId, Name, and ProductNumber from the Product table for which the value in the column SafetyStockLevel is equal or greater than the value passed in the function’s parameter.

上面的代码部分从Product表中返回诸如ProductId,Name和ProductNumber之类的数据,其数据在SafetyStockLevel列中的值等于或大于在函数的参数中传递的值。

We can find out the udfGetProductList function under the Programmability folder in SQL Server Management Studio.

我们可以在SQL Server Management Studio的Programmability文件夹下找到udfGetProductList函数。

SQL Server Management Studio table-valued functions location

As you can see in the above image, SSMS also shows the parameters information of the iTVF.

如上图所示,SSMS还显示了iTVF的参数信息。

执行内联表值函数 (Executing an inline table-valued function)

Through the following query, we can execute the TVF. We should mark one thing again that the resultset of the function will be changed according to @SafetyStockLevel parameter.

通过以下查询,我们可以执行TVF。 我们应该再次标记一件事,即函数的结果集将根据@SafetyStockLevel参数进行更改。

SELECT *FROM dbo.udfGetProductList( 100 )

Resultset illustration of the table-valued function

In the above case, we passed the @SafetyStockLevel as 100 and the udfGetProductList function returned a resultset according to this parameter. In the below example, we will add a WHERE clause to query so that we can apply to filter the output of the function.

在上述情况下,我们将@SafetyStockLevel传递为100,并且udfGetProductList函数根据此参数返回了一个结果集。 在下面的示例中,我们将添加WHERE子句进行查询,以便我们可以应用该函数来过滤函数的输出。

SELECT *FROM dbo.udfGetProductList( 100 )WHERE Name LIKE 'Chainring%'

Usage of the table-valued function with where clause

In the following example, we will use the JOIN clause with the udfGetProductList function.

在下面的示例中,我们将在udfGetProductList函数中使用JOIN子句。

SELECT PUdfList.ProductNumber, PUdfList.Name, PCost.StandardCostFROM dbo.udfGetProductList( 100 ) AS PUdfList   INNER JOIN   Production.ProductCostHistory AS PCost   ON PUdfList.ProductId = PCost.ProductIDWHERE PUdfList.ProductId = 717

Usage of the table-valued function with join clause

In the above case, we joined the ProductCostHistory table and udfGetProductList and added the StandartCost column to the resultset from ProductCostHistory table.

在上述情况下,我们加入了ProductCostHistory表和udfGetProductList并将StandartCost列添加到ProductCostHistory表的结果集中

默认参数的用法 (Usage of the default parameter)

We learned that the inline table-valued functions accept parameters and these parameters must be passed to the functions in order to execute them. However, we can declare default parameter values for iTVFs. If we want to execute a function with a default value, we should set a default value and we can set this value to the function with the help of the DEFAULT keyword. In the following example, we will alter the udfGetProductList function and declare a new parameter with a default value. In this way, we do not need to give any value to the parameter. Solely, we will pass the DEFAULT keyword instead of the parameter value.

我们了解到, 内联表值函数接受参数,并且必须将这些参数传递给函数才能执行它们。 但是,我们可以为iTVF声明默认参数值。 如果要使用默认值执行函数,则应设置默认值,并可以借助DEFAULT关键字将此值设置为函数。 在下面的示例中,我们将更改udfGetProductList函数,并声明一个具有默认值的新参数。 这样,我们不需要给参数赋任何值。 仅此,我们将传递DEFAULT关键字而不是参数值。

ALTER FUNCTION [dbo].[udfGetProductList](@SafetyStockLevel SMALLINT , @MFlag BIT=0)RETURNS TABLEASRETURN(SELECT Product.ProductID,         Product.Name,         Product.ProductNumber FROM Production.Product WHERE SafetyStockLevel >= @SafetyStockLevel AND MakeFlag=@MFlag )

In the above usage scenario, we added a new parameter to udfGetProductList function whose name is @MFlag and this parameter default value is specified as 0.

在上述使用场景中,我们向udfGetProductList函数添加了一个新参数,其名称为@MFlag,并且该参数的默认值指定为0。

Now let’s learn how to execute the udfGetProductList function with the default parameter. The following query shows this usage method:

现在,让我们学习如何使用默认参数执行udfGetProductList函数。 以下查询显示此用法:

SELECT *FROM dbo.udfGetProductList( 100, DEFAULT )

Usage of the table-valued function with default syntax

如何将多个参数传递给内联表值函数 (How to pass multiple parameters into an Inline table-valued function)

In some cases, we need to pass multiple parameter values to iTVFs. Assume that the development team wants to pass multiple values in one parameter into the designed function. To perform a usage scenario like this, we must create a user-defined table type because through these types we gain an ability to declare . Table-valued parameters allow sending multiple values to functions.

在某些情况下,我们需要将多个参数值传递给iTVF 。 假设开发团队希望将一个参数中的多个值传递给设计的函数。 要执行这样的使用场景,我们必须创建一个用户定义的表类型,因为通过这些类型,我们可以声明 。 表值参数允许将多个值发送到函数。

  • Creating a user-defined table type:

    创建用户定义的表类型:

    CREATE TYPE ProductNumberList AS TABLE( ProductNum nvarchar(25))
  • Adding the table-valued to udfGetProductList function with READONLY statement:

    使用READONLY语句将表值添加到udfGetProductList函数:

    ALTER FUNCTION [dbo].[udfGetProductList](         @SafetyStockLevel SMALLINT, @MFlag BIT= 0, @ProductList ProductNumberList READONLY)RETURNS TABLEASRETURN(SELECT Product.ProductID, Product.Name, Product.ProductNumber FROM Production.Product WHERE SafetyStockLevel >= @SafetyStockLevel     AND MakeFlag = @MFlag     AND Product.ProductNumber IN (   SELECT ProductNum   FROM @ProductList ))
  • Declare a variable as a table-valued parameter and populate it with multiple parameter values. Execute the function.

    将变量声明为表值参数,并使用多个参数值填充该变量。 执行功能。

    DECLARE @TempProductList AS ProductNumberListINSERT INTO @TempProductListVALUES( 'EC-R098' ), ( 'EC-T209' ) SELECT * FROM [dbo].[udfGetProductList](100,1,@TempProductList)

Usage of the table-valued function with table-valued parameter

结论 (Conclusion)

In this article, we explored why we should use functions in SQL Server and then learned the usage scenarios of the inline table-valued functions (iTVF). These types of functions make our database development process easier and modular and also, they help to avoid re-write the same code again.

在本文中,我们探讨了为什么要在SQL Server中使用函数,然后了解了内联表值函数(iTVF)的使用方案。 这些类型的功能使我们的数据库开发过程更加轻松和模块化,并且有助于避免再次重写同一代码。

翻译自:

转载地址:http://ppnwd.baihongyu.com/

你可能感兴趣的文章
TestNG(五)常用元素的操作
查看>>
解决 Visual Studio 点击添加引用无反应的问题
查看>>
通过镜像下载Android系统源码
查看>>
python字符串格式化 %操作符 {}操作符---总结
查看>>
windows 不能在 本地计算机 启动 Apache
查看>>
iOS开发报duplicate symbols for architecture x86_64错误的问题
查看>>
Chap-6 6.4.2 堆和栈
查看>>
【Java学习笔记之九】java二维数组及其多维数组的内存应用拓展延伸
查看>>
C# MySql 连接
查看>>
sk_buff Structure
查看>>
oracle的级联更新、删除
查看>>
多浏览器开发需要注意的问题之一
查看>>
Maven配置
查看>>
HttpServletRequest /HttpServletResponse
查看>>
SAM4E单片机之旅——24、使用DSP库求向量数量积
查看>>
从远程库克隆库
查看>>
codeforces Unusual Product
查看>>
hdu4348 - To the moon 可持久化线段树 区间修改 离线处理
查看>>
springMVC中一个class中的多个方法
查看>>
cxx signal信号捕获
查看>>