My stored procedure has an output parameter:
@ID INT OUT
How can I retrieve this using ado.net?
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
Create the SqlParamObject which would give you control to access methods on the parameters
:
SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)
:
param.ParameterName = "@yourParamterName";
Clear the value holder to hold you output data
:
param.Value = 0;
Set the Direction of your Choice (In your case it should be Output)
:
param.Direction = System.Data.ParameterDirection.Output;
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
That looks more explicit for me:
The other response shows this, but essentially you just need to create a
SqlParameter
, set theDirection
toOutput
, and add it to theSqlCommand
'sParameters
collection. Then execute the stored procedure and get the value of the parameter.Using your code sample:
Be careful when getting the
Parameters[].Value
, since the type needs to be cast fromobject
to what you're declaring it as. And theSqlDbType
used when you create theSqlParameter
needs to match the type in the database. If you're going to just output it to the console, you may just be usingParameters["@Param"].Value.ToString()
(either explictly or implicitly via aConsole.Write()
orString.Format()
call).EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.
You can get your result by below code::