Accessing Output Parameter Values with ADO.NET
This guide demonstrates how to effectively retrieve output parameter values within an ADO.NET application. Properly handling output parameters is crucial for many database interactions.
Defining Output Parameters in Stored Procedures
To declare an output parameter in your stored procedure, utilize this syntax:
<code class="language-sql">@ParameterName DATATYPE OUTPUT</code>
Example:
<code class="language-sql">@ID INT OUTPUT</code>
Retrieving Output Parameter Values in ADO.NET Code
The following steps detail how to access the output parameter value in your C# code:
<code class="language-csharp">// Create a SqlParameter for the output parameter, specifying name, type, and direction. SqlParameter outputParameter = new SqlParameter("@ID", SqlDbType.Int); outputParameter.Direction = ParameterDirection.Output; // Add the output parameter to the SqlCommand's Parameters collection. cmd.Parameters.Add(outputParameter); // Execute the stored procedure. cmd.ExecuteNonQuery(); // Access the output parameter's value after execution. int id = (int)outputParameter.Value; </code>
Important Notes:
SqlDbType
used when creating the SqlParameter
must precisely match the data type of the output parameter in your stored procedure.outputParameter.Value
to the correct data type (e.g., int
, string
, DateTime
).null
value. This prevents runtime errors.The above is the detailed content of How to Retrieve Output Parameter Values in ADO.NET?. For more information, please follow other related articles on the PHP Chinese website!