共用方式為


HOW TO:使用接受參數的預存程序 (LINQ to SQL)

更新: November 2007

LINQ to SQL 會將輸出參數對應至參考參數,而且會針對實值型別 (Value Type),將參數宣告為可為 Null。

如需如何在查詢中使用輸入參數以傳回資料列集 (Rowset) 的範例,請參閱 HOW TO:使用預存程序傳回資料列集 (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));
    }

您可如下呼叫這個預存程序 (Stored Procedure):

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)