我有一個存儲過程,我希望它返回一列值的總和。當我使用SqlCommand
時,我添加了參數enrollmentId
。當我嘗試在Visual Studio中運行我的代碼時,它說我必須提供參數@totalEarned
...我的問題是,這是我使用SP來確定...它應該輸出@totalEarned
。如何在不提供@totalEarned
的情況下使用此SP?如何從ASP C#中的標量存儲過程獲取返回值?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[totalEarned]
@enrollmentId Int,
@totalEarned int OUTPUT
AS
BEGIN
SELECT @totalEarned = SUM(pointsEarned)
FROM Assignments
WHERE enrollmentId = @enrollmentId
RETURN
END
這裏的C#代碼:
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.totalEarned", conn);
cmd.Parameters.Add(new SqlParameter("@enrollmentId", enrollmentId));
cmd.Parameters.Add(new SqlParameter("@totalEarned", null));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (conn)
{
conn.Open();
double totalEarned = (double)cmd.ExecuteScalar();
}
而不是使用的輸出,改變你回'回報@ totalEarned' –
是啊,我意識到,但它仍然給我同樣的信息。 – ShoeLace1291
也從SP參數中刪除它。在SQL中你根本不需要它@totalEarned,但是如果它使代碼更清晰,你可以將它作爲DECLARE。 –