SQL用户定义的函数
问题描述:
在SQL中table valued
功能为什么不能我们写里面begin
SQL语句和end
标签喜欢 -SQL用户定义的函数
create function dbo.emptable()
returns Table
as
BEGIN --it throws an error
return (select id, name, salary from employee)
END
go
而在scalar valued
功能,我们可以使用这些标签,如
create function dbo.countemp()
returns int
as
begin
return (select count(*) from employee)
end
go
有什么具体的规则我们应该使用BEGIN & END
标签
答
多语句表值函数 稍微复杂 比其他两种类型的功能 ,因为它使用多个语句 建立返回给 调用语句中的表。与 内嵌表值函数不同,必须明确声明 变量并定义该变量。以下示例 显示如何实现填充并返回表 变量的多语句表值函数 。
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
根据上述内容,我想BEGIN
和END
表示意图/使用多个语句&的,因此它需要如图上面的代码要定义的表的变量。
from http://www.sqlteam.com/article/intro-to-user-defined-functions-updated
答
在INLI NE TVF(就像你的第一个例子),BEGIN
和END
会试图强制它成为程序代码,因此它不再是一个Inline TVF。标量函数只能以过程形式提供(这很糟糕)。因此,在当前版本的SQL Server中通常应避免使用标量函数。