I have created a stored procedure similar to this simplified example:
CREATE PROCEDURE dbo.sp_MyStoredProcedure
@Var1 INT OUTPUT,
@Var2 DECIMAL(10,2) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT
@Var1 = COUNT(*),
@Var2 = SUM(TranAmount)
FROM
MyTable
SELECT * FROM MyTable
END
When I try to read the values from the output variables after I call the ExecuteReader()
method of the SqlCommand
object, the values are null.
string MyConnString = string.Empty;
SqlConnection MyConn = new SqlConnection(MyConnString);
SqlCommand MyCmd = new SqlCommand("sp_MyStoredProcedure", MyConn);
MyCmd.CommandType = CommandType.StoredProcedure;
MyCmd.Parameters.Add(new SqlParameter("@Var1", SqlDbType.Int));
MyCmd.Parameters.Add(new SqlParameter("@Var2", SqlDbType.Decimal);
MyCmd.Parameters[0].Direction = ParameterDirection.Output;
MyCmd.Parameters[1].Direction = ParameterDirection.Output;
SqlDataReader dr = MyCmd.ExecuteReader(CommandBehavior.CloseConnection);
int Var1 = Convert.ToInt32(MyCmd.Parameters[0].Value);
decimal Var1 = Convert.ToDecimal(MyCmd.Parameters[1].Value);
What I am doing wrong?