如何:使用带参数的存储过程 (LINQ to SQL)

更新:November 2007

LINQ to SQL 将输出参数映射到引用参数,并且对于值类型,它将参数声明为可以为 null。

有关如何在返回行集的查询中使用输入参数的示例,请参见如何:使用存储过程返回行集 (LINQ to SQL)

示例

下面的示例带有单个输入参数(客户 ID)并返回一个输出参数(该客户的总销售额)。

CREATE PROCEDURE [dbo].[CustOrderTotal] 
@CustomerID nchar(5),
@TotalSales money OUTPUT
AS
SELECT @TotalSales = SUM(OD.UNITPRICE*(1-OD.DISCOUNT) * OD.QUANTITY)
FROM ORDERS O, "ORDER DETAILS" OD
where O.CUSTOMERID = @CustomerID AND O.ORDERID = OD.ORDERID
<FunctionAttribute(Name:="dbo.CustOrderTotal")> _
 Public Function CustOrderTotal(<Parameter(Name:="CustomerID", DbType:="NChar(5)")> ByVal customerID As String, <Parameter(Name:="TotalSales", DbType:="Money")> ByRef totalSales As System.Nullable(Of Decimal)) As <Parameter(DbType:="Int")> Integer
    Dim result As IExecuteResult = Me.ExecuteMethodCall(Me, CType(MethodInfo.GetCurrentMethod, MethodInfo), customerID, totalSales)
    totalSales = CType(result.GetParameterValue(1), System.Nullable(Of Decimal))
    Return CType(result.ReturnValue, Integer)
End Function
    [Function(Name="dbo.CustOrderTotal")]
    [return: Parameter(DbType="Int")]
    public int CustOrderTotal([Parameter(Name="CustomerID", DbType="NChar(5)")] string customerID, [Parameter(Name="TotalSales", DbType="Money")] ref System.Nullable<decimal> totalSales)
    {
        IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID, totalSales);
        totalSales = ((System.Nullable<decimal>)(result.GetParameterValue(1)));
        return ((int)(result.ReturnValue));
    }

您将按如下方式调用此存储过程:

Dim db As New Northwnd("C:\...\northwnd.mdf")
Dim totalSales As Decimal? = 0
db.CustOrderTotal("alfki", totalSales)

Console.WriteLine(totalSales)
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
decimal? totalSales = 0;
db.CustOrderTotal("alfki", ref totalSales);

Console.WriteLine(totalSales);

请参见

概念

下载示例数据库 (LINQ to SQL)

可以为 Null 的值类型

参考

使用可以为 null 的类型(C# 编程指南)

其他资源

存储过程 (LINQ to SQL)