3.使用用户定义的表值函数 表值函数返回单个行集(与存储过程不同,存储过程可返回多个结果形状)。由于表值函数的返回类型为 Table,因此在 SQL 中可以使用表的任何地方均可以使用表值函数。此外,您还可以完全像处理表那样来处理表值函数。
下面的 SQL 用户定义函数显式声明其返回一个 TABLE。因此,隐式定义了所返回的行集结构。
ALTER FUNCTION [dbo].[ProductsUnderThisUnitPrice]
(@price Money
)
RETURNS TABLE
AS
RETURN
SELECT *
FROM Products as P
Where p.UnitPrice < @price
拖到设计器中,LINQ to SQL 按如下方式映射此函数:
[Function(Name="dbo.ProductsUnderThisUnitPrice", IsComposable=true)]
public IQueryable<ProductsUnderThisUnitPriceResult> ProductsUnderThisUnitPrice(
[Parameter(DbType="Money")] System.Nullable<decimal> price)
{
return this.CreateMethodCallQuery<ProductsUnderThisUnitPriceResult>(
this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), price);
}
这时我们小小的修改一下Discontinued属性为可空的bool类型。
private System.Nullable<bool> _Discontinued;
public System.Nullable<bool> Discontinued
{
}
我们可以这样调用使用了:
var q = from p in db.ProductsUnderThisUnitPrice(10.25M)
where !(p.Discontinued ?? false)
select p;
其生成SQL语句如下:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID],
[t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice],
[t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel],
[t0].[Discontinued]
FROM [dbo].[ProductsUnderThisUnitPrice](@p0) AS [t0]
WHERE NOT ((COALESCE([t0].[Discontinued],@p1)) = 1)
-- @p0: Input Money (Size = 0; Prec = 19; Scale = 4) [10.25]
-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [0]