How can I get return value of stored procedure when using SqlDataReader?

12,563

Agh. I've found out the reader has to be closed to get the return value! So inside the if {} block above, I added:

myReader.Close(); // Need to close data reader before getting return value.
int returnValue = (int)myCommand.Parameters["@returnValue"].Value;

...and now it works OK!

Share:
12,563
NickG
Author by

NickG

ASP.NET Website Developer for a small software company in Winchester, Hampshire (UK).

Updated on June 14, 2022

Comments

  • NickG
    NickG about 2 years

    Is it not possible to get the return value of a stored procedeure when using a datareader? The return value is always null, but the SP returns a valid int from within SSMS.

    myCommand.CommandText = "GetVenueVideos";
    SqlParameter retVal = new SqlParameter("@returnValue",SqlDbType.Int);
    retVal.Direction = ParameterDirection.ReturnValue;
    myCommand.Parameters.Add(retVal);
    myReader = myCommand.ExecuteReader();
    if (myReader.Read() && myReader.HasRows)
    {
        int returnValue = Convert.ToInt32(retVal.Value);
        //returnValue is null at this point
    }
    
  • LukeH
    LukeH over 12 years
    This is actually documented on MSDN, although not very prominently. For example, see the "Remarks" section of msdn.microsoft.com/en-us/library/… or the "Closing the DataReader" section of msdn.microsoft.com/en-us/library/haa3afyz.aspx.
  • Nikos Baxevanis
    Nikos Baxevanis over 8 years
    Very nice! Closing the DataReader did the trick for me as well.