2010-06-17 60 views
2

在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標籤

回答

0

多語句表值函數 稍微複雜 比其他兩種類型的功能 ,因爲它使用多個語句 建立返回給 調用語句中的表。與 內嵌表值函數不同,必須明確聲明 變量並定義該變量。以下示例 顯示如何實現填充並返回表 變量的多語句表值函數 。

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 

根據上述內容,我想BEGINEND表示意圖/使用多個語句&的,因此它需要如圖上面的代碼要定義的表的變量。

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

0

在INLI NE TVF(就像你的第一個例子),BEGINEND會試圖強制它成爲程序代碼,因此它不再是一個Inline TVF。標量函數只能以過程形式提供(這很糟糕)。因此,在當前版本的SQL Server中通常應避免使用標量函數。