Home >Database >Mysql Tutorial >How to Retrieve Return Values from Stored Procedures in C#?
Retrieving Return Values from Stored Procedures in C#
This article explores how to retrieve return values from stored procedures in C#.
Let's consider the following stored procedure named "[dbo].[Validate]":
ALTER PROCEDURE [dbo].[Validate] @a varchar(50), @b varchar(50) output AS SET @Password = (SELECT Password FROM dbo.tblUser WHERE Login = @a) RETURN @b
To execute this stored procedure and retrieve the return value, you can use the following code:
using System; using System.Data; using System.Data.SqlClient; namespace StoredProcedureReturnValue { class Program { static void Main(string[] args) { // Assuming you have a connection string defined in your app config string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString; // Create a connection and command object using (SqlConnection SqlConn = new SqlConnection(connectionString)) using (SqlCommand sqlcomm = new SqlCommand("Validate", SqlConn)) { // Specify the stored procedure sqlcomm.CommandType = CommandType.StoredProcedure; // Add input parameters SqlParameter inputParam = new SqlParameter("@a", SqlDbType.VarChar, 50); inputParam.Value = "myUsername"; sqlcomm.Parameters.Add(inputParam); // Add an output parameter to receive the return value SqlParameter outputParam = new SqlParameter("@b", SqlDbType.VarChar, 50); outputParam.Direction = ParameterDirection.ReturnValue; sqlcomm.Parameters.Add(outputParam); // Open the connection and execute the stored procedure SqlConn.Open(); sqlcomm.ExecuteNonQuery(); // Retrieve the output value string returnValue = (string)outputParam.Value; // Do something with the return value Console.WriteLine($"Return value: {returnValue}"); } } } }
Key points to note:
The above is the detailed content of How to Retrieve Return Values from Stored Procedures in C#?. For more information, please follow other related articles on the PHP Chinese website!