作法:使用有參數的預存程序
LINQ to SQL 會將輸出參數對應至參考參數,而且會針對實值型別將參數宣告為可為 Null。
如需如何在查詢中使用輸入參數以傳回資料列集的範例,請參閱如何:傳回資料列集。
範例 1
下列範例取用單一輸入參數 (客戶 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
[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));
}
<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
範例 2
您可如下呼叫這個預存程序 (Stored Procedure):
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
decimal? totalSales = 0;
db.CustOrderTotal("alfki", ref totalSales);
Console.WriteLine(totalSales);
Dim db As New Northwnd("C:\...\northwnd.mdf")
Dim totalSales As Decimal? = 0
db.CustOrderTotal("alfki", totalSales)
Console.WriteLine(totalSales)