User Define Function, 使用者自訂函數,簡稱UDF. 關於sql server中的udf,請大家參考 http://msdn.microsoft.com/msdnmag/issues/03/11/DataPoints/一文。本文主要闡述,在Linq To Sql 中,如何使用UDF.
1,UDF 簡介
UDF可以分為兩中類型。一種為Scalar Valued Function,簡稱為SVF,是傳回值類型的UDF. 另一種 為Table Valued Function 簡稱為TVF,是返回一個table的UDF. 人們通常喜歡拿UDF和Store Procedure 做比較。其實,他們各有千秋。UDF最多隻能返回一個RowSet,而Store Procedure可以是多個。Store Procedure支援CUD操作,而UDF不支援。但是UDF在sql 中支援內聯查詢,這個又是Sprocs所不能及的。 因此Linq To Sql 也支援UDF的內聯查詢。
2,SVF
看下面這個例子。返回某個類別產品最小的單元價格。
CREATE FUNCTION [dbo].[MinUnitPriceByCategory]
(@categoryID INT
)
RETURNS Money
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar Money
-- Add the T-SQL statements to compute the return value here
SELECT @ResultVar = MIN(p.UnitPrice) FROM Products as p WHERE p.CategoryID = @categoryID
-- Return the result of the function
RETURN @ResultVar
END
用OR Designer(請參考OR工具介紹 )將其映射為Dbml。如下
<Function Name="dbo.MinUnitPriceByCategory" Method="MinUnitPriceByCategory" IsComposable="true">
<Parameter Name="categoryID" Type="System.Int32" DbType="Int" />
<Return Type="System.Decimal" />
</Function>