简体   繁体   English

sql用户定义函数

[英]sql user defined function

for a table valued function in sql why cant we write sql statements inside begin and end tags like- 对于sql中的table valued函数,为什么不能在beginend标记内编写sql语句,例如-

create function dbo.emptable()
returns Table
as
BEGIN --it throws an error
return (select id, name, salary from employee)
END
go

while in scalar valued function we can use these tags like 而在scalar valued函数中,我们可以使用这些标签,例如

create function dbo.countemp()
returns int
as
begin
return (select count(*) from employee)
end
go

is there any specific rule where we should use BEGIN & END tags 是否有任何特定规则应使用BEGIN & END标签

In an INLINE TVF (like your first example), the BEGIN and END would try to force it to be procedural code, and therefore it would no longer be an Inline TVF. 在INLINE TVF(如您的第一个示例)中, BEGINEND会尝试将其强制为过程代码,因此它将不再是Inline TVF。 Scalar functions are only available in a procedural form (which is lousy). 标量函数仅以过程形式(糟糕的)可用。 Therefore, Scalar functions should generally be avoided in the current versions of SQL Server. 因此,通常应在当前版本的SQL Server中避免使用标量函数。

The multi-statement table-valued function is slightly more complicated than the other two types of functions because it uses multiple statements to build the table that is returned to the calling statement. 多语句表值函数比其他两种类型的函数稍微复杂一点,因为它使用多个语句来构建返回到调用语句的表。 Unlike the inline table-valued function, a table variable must be explicitly declared and defined. 与内联表值函数不同,必须显式声明和定义表变量。 The following example shows how to implement a multi-statement table-valued function that populates and returns a table variable. 下面的示例演示如何实现填充并返回表变量的多语句表值函数。

USE Northwind
go
CREATE FUNCTION fx_OrdersByDateRangeAndCount
( @OrderDateStart smalldatetime, 
  @OrderDateEnd smalldatetime, 
  @OrderCount smallint )
RETURNS @OrdersByDateRange TABLE
  (  CustomerID nchar(5),
     CompanyName nvarchar(40),
     OrderCount smallint,
     Ranking char(1) )
AS
BEGIN
// statements that does some processing ....

END

From the above, I guess BEGIN and END denotes the intent/use of multiple statements & hence it requires the table variable to be defined as shown in the code above. 从上面的内容,我想BEGINEND表示意图/使用多个语句,因此,它需要如上面的代码所示定义表变量。

from http://www.sqlteam.com/article/intro-to-user-defined-functions-updated 来自http://www.sqlteam.com/article/intro-to-user-defined-functions-updated

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM