Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a returned value and a set of record in C# when calling a stored procedure

I have a stored procedure that returns 2 output parameters and a record.

But in C#:

  • ExecuteReader won't allow a returned value but allows records
  • ExecuteNonQuery allows a returned value but not record.

How can I get both?

like image 831
Walloud Avatar asked Mar 22 '23 08:03

Walloud


1 Answers

The output parameter returned by a stored procedure are not available until you close the DataReader.

Supposing you have

 SqlDataReader reader = cmd.ExecuteReader();
  ...... do you record reading
 reader.Close();

 // Now the output parameters are available
 int result = (int)cmd.Parameters["OutputParameter1"].Value;         

Of course this is supposing that you have correctly setup your output parameters....

This is from SqlDataReader docs on MSDN

While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.

like image 69
Steve Avatar answered Apr 16 '23 20:04

Steve