Return value parameter returns null

I was really confused this morning. I was executing a stored proc that returned a single row of data, and a return value. However, the return value was always null - even though the stored proc ALWAYS returned a return value. The code was domething like this:

C#:
  1. SqlParameter retval = new SqlParameter("@RETURN_VALUE", SqlDbType.Int);
  2. retval.Direction = ParameterDirection.ReturnValue;
  3. command1.Parameters.Add(retval);
  4.  
  5. using (SqlDataReader reader = command1.ExecuteReader())
  6. {
  7.     if (reader.Read())
  8.     {
  9.         var1 = reader["Col1"].ToString();
  10.         var2 = reader["col2"].ToString();
  11.     }
  12.     if (retval.Value != null)
  13.         errorCode = Convert.ToInt32(retval.Value);
  14.     else
  15.         errorCode = -1;
  16. }

It turns out that you need to close the reader before you can access the return value parameter.
From MSDN Library: SqlDataReader.Close()

The Close method fills in the values for output parameters, return values and RecordsAffected...

I can see why it's been implemented like that (the return value, output parameters and number of records affected come at the end, after the result set) - but I have to say it is counter-intuitive to have to close the reader before you can access these values.

Leave a Reply