如何从ASP C#中的标量存储过程中获取返回值?

时间:2016-03-05 07:44:44

标签: c# asp.net sql-server

我有一个存储过程,我希望它返回一列值的总和。当我使用SqlCommand时,我添加参数enrollmentId。当我尝试在Visual Studio中运行我的代码时,它说我必须提供参数@totalEarned ...我的问题是我正在使用SP来确定...它应该输出{{ 1}}。如何在不提供@totalEarned的情况下使用此SP?

@totalEarned

这是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

2 个答案:

答案 0 :(得分:2)

您必须指定Direction。将cmd.Parameters.Add(new SqlParameter("@totalEarned", null));替换为:

SqlParameter totalEarned= new SqlParameter("@totalEarned", SqlDbType.Int);
totalEarned.Direction = ParameterDirection.Output;
cmd.Parameters.Add(totalEarned);  

然后在执行命令后,将其强制转换为int以获取值:

int value = (int)totalEarned.Value;

答案 1 :(得分:1)

构建SqlParameter时,将其Direction属性设置为Output

或者,只需直接SELECT SUM(pointsEarned)