Tuesday, February 24, 2009

Getting output paramater with ExecuteReader()

When you have a stored procedure that return both a result set and a return value, and you use ExecuteReader() to get the result set, you can only get the output parameter when you close the reader!

http://support.microsoft.com/kb/310070

SqlCommand sqcMyProc = new SqlCommand("[dbo].spMyProc", sqDBConnection);
sqcMyProc.CommandType = CommandType.StoredProcedure;
sqcMyProc.Parameters.Add(new SqlParameter("@nSomeParam", SqlDbType.BigInt));
sqcMyProc.Parameters["Result"].Direction = ParameterDirection.ReturnValue;
sqcMyProc.Prepare();
SqlDataReader sqrMyProcReader = sqcMyProc.ExecuteReader();
if (sqrMyProcReader.Read())
{
// read data
}
sqrMyProcReader.Close(); // output param only available after closing reader

(int)sqcMyProc.Parameters["Result"].Value; // here is the return value

No comments:

Post a Comment