Linq To Sql进阶系列(四)User Define Function篇2011-08-20 博客园 Tom SongUser 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