Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 493
NickG Avatar asked Nov 11 '11 11:11

NickG


People also ask

What does SqlDataReader return?

As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row Once a row has been read, the previous row is no longer available.

How can we return a value in stored procedure?

You can use one or more RETURN statements in a stored procedure. The RETURN statement can be used anywhere after the declaration blocks within the SQL-procedure-body. To return multiple output values, parameters can be used instead. Parameter values must be set prior to the RETURN statement being executed.

Does stored procedure have return value?

Stored procedures do not have a return value but can take a list with input, output, and input-output parameters.

Can we return from stored procedure?

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero.


1 Answers

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!

like image 106
NickG Avatar answered Nov 07 '22 23:11

NickG