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 注意:要了解有关多语句表值函数的更多信息,请参阅SQL Server multi-statement table-valued functions articleSQL Server多语句表值函数文章

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, SQL Server built-in functions and user-defined scalar functions, to gain knowledge about built-in functions and user-defined scalar functions in SQL Server.

您可以直接参考本文SQL Server内置函数和用户定义的标量函数 ,以获取有关SQL Server中的内置函数和用户定义的标量函数的知识。

Note: All the examples of this article will be used on the Adventureworks sample database and queries formatted in the ApexSQL Online SQL formatter.

注意:本文的 所有示例都将在 Adventureworks 示例数据库中 使用, 并以 ApexSQL Online SQL格式器格式化 查询

创建内联表值函数(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 TABLE
AS
RETURN
(SELECT Product.ProductID, Product.Name, Product.ProductNumberFROM Production.ProductWHERE 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.ProductNumberFROM Production.ProductWHERE 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函数。

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 )

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%'

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

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

SELECT PUdfList.ProductNumber, PUdfList.Name, PCost.StandardCost
FROM dbo.udfGetProductList( 100 ) AS PUdfListINNER JOINProduction.ProductCostHistory AS PCostON PUdfList.ProductId = PCost.ProductID
WHERE PUdfList.ProductId = 717

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 TABLE
AS
RETURN
(SELECT Product.ProductID, Product.Name, Product.ProductNumberFROM Production.ProductWHERE SafetyStockLevel >= @SafetyStockLevelAND 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 )

如何将多个参数传递给内联表值函数 (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. 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 TABLE
    AS
    RETURN
    (SELECT Product.ProductID, Product.Name, Product.ProductNumberFROM Production.ProductWHERE SafetyStockLevel >= @SafetyStockLevelAND MakeFlag = @MFlagAND Product.ProductNumber IN(SELECT ProductNumFROM @ProductList))
    
  • Declare a variable as a table-valued parameter and populate it with multiple parameter values. Execute the function.

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

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

结论 (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)的使用方案。 这些类型的功能使我们的数据库开发过程更加轻松和模块化,并且有助于避免再次重写同一代码。

翻译自: https://www.sqlshack.com/sql-server-inline-table-valued-function/

SQL Server内联表值函数相关推荐

  1. SQL server内嵌表值函数与多语句表值函数

    内联表值函数 create function 函数名(@变量 as 类型) returns table as return ( 结果集[select查询语句] ) go select 列名 from ...

  2. SQL Server多语句表值函数

    In this article, we will learn multi-statement table-valued functions (MSTVFs) basics and then we wi ...

  3. 多语句表值函数与内联表值函数区别?

    有几个例子要展示,以防万一: 内联表值 CREATE FUNCTION MyNS.GetUnshippedOrders() RETURNS TABLE AS RETURN SELECT a.SaleI ...

  4. mysql 实现表值函数,SQL SERVER 的 CLR表值函数

    一.使用CLR表值 函数 的背景 在SQL SERVER里面,直接读取远程 数据库 的表,似乎会占用大量的内存,出现类似错误: 链接服务器 192.168.0.1 的 OLE DB 访问接口 SQLN ...

  5. SQL Server中的STRING_SPLIT函数

    This article will cover the STRING_SPLIT function in SQL Server including an overview and detailed u ...

  6. sql server编程之 T-SQL函数

    T-SQL函数 学习系统函数.行集函数和Ranking函数:重点掌握字符串函数.日期时间函数和数学函数的使用参数以及使用技巧 重点掌握用户定义的标量函数以及自定义函数的执行方法 掌握用户定义的内嵌表值 ...

  7. 什么是SQL Server TRIM()函数?

    Hello, readers. In today's article, we will be focusing on SQL Server TRIM() function in detail. 您好, ...

  8. C++类的内联成员函数应放在哪

    今天复习C++ Primer的时候,看到了关于C++类的内联成员函数的放置,应该放在头文件中.那么这到底是为什么 呢?仅仅是一种代码规范问题还是必须这样做呢? 下面我就来讲讲我自己的理解吧.要彻底理解 ...

  9. 标量函数,多语句表值函数,内嵌表值函数

    标量函数返回一个标量(单值)结果,可返回Timestamp,text,Ntext,Image,Table,Cursor 多语句表值函数,返回一条或多条Transact-sql语句建立的表,可在sele ...

最新文章

  1. 【Pytorch神经网络实战案例】26 MaskR-CNN内置模型实现目标检测
  2. 七、gradle依赖管理
  3. 阿里云宣布与Facebook达成合作 让AI开发更简单
  4. Java只读服务器,在服务器端,JSP页面如何只读打开本地的word文件并显示在网页上...
  5. 软件工程学习进度第四周暨暑期学习进度之第四周汇总
  6. javaSE_06Java中的数组(array)-思维导图
  7. LeetCode——Find Minimum in Rotated Sorted Array II
  8. spring页面使用注解@RequestParam把请求参数封装到map中
  9. Spring身份验证+CXF拦截器+RESTful
  10. powershell 模拟IE行为
  11. unity Curvy Splines基础操作:创建可视赛道
  12. Arcgis实例学习5--统计直方图、空间分布图、统计信息
  13. 深圳赛意信息 怎么样_深圳鹏程整形医院怎么样_全新整形价目表_资质
  14. Java_String_Arrays_Character_BigDecimal_Calendar_Math_System
  15. 启动zkCli.sh时指定IP地址
  16. [Vue.js] 一篇超级长的笔记,给《Vue.js 实战》划个重点
  17. 程序员的520,送给女友的几行漂亮的代码(js版)
  18. 实力领航|万应智谷云平台成功入选2022中国互联网大会“互联网助力经济社会数字化转型”特色案例
  19. 刚子扯谈:酒装狗熊胆
  20. 弹球游戏过关之缩短挡板(三)

热门文章

  1. python中dir用法_Python dir() 函数
  2. newifimini出厂固件_新路由mini固件|newifi新路由mini OS固件V3.2.1.1100 抢先版 - 极光下载站...
  3. linux gpsd 授时原理,app/ntp/gps/README.md · 王者归来/ITTS - Gitee.com
  4. label包裹input,点击label响应两次解决方法
  5. Uva 10817 校长的烦恼
  6. bzoj1562[NOI2009] 变换序列
  7. [转载]Memcached缓存服务的简单安装
  8. 前端性能优化之缓存技术
  9. mysql自增主键返回---创建成功后返回用户的ID
  10. 小程序本地图片偶尔加载不出来_小程序优化的20中策略