Home >Backend Development >C++ >How to Retrieve Stored Procedure Return Values in C#?
When calling a stored procedure that returns a value in C#, it is crucial to correctly handle the return value in the code. This article describes this problem and provides a solution for successfully retrieving return values from stored procedures.
A C# application needs to call a stored procedure that returns the next value in a sequence. Despite following the solutions online, I still cannot retrieve the return value. The provided code snippet includes creating a SqlCommand object, specifying the stored procedure as the command text, and using a SqlConnection to execute the command. However, the return value of the stored procedure is not retrieved.
<code class="language-sql">ALTER procedure [dbo].[usp_GetNewSeqVal] @SeqName nvarchar(255) as begin declare @NewSeqVal int set NOCOUNT ON update AllSequences set @NewSeqVal = CurrVal = CurrVal+Incr where SeqName = @SeqName if @@rowcount = 0 begin print 'Sequence does not exist' return end return @NewSeqVal end</code>
<code class="language-csharp">SqlConnection conn = new SqlConnection(getConnectionString()); conn.Open(); SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter(); param = cmd.Parameters.Add("@SeqName", SqlDbType.NVarChar); param.Direction = ParameterDirection.Input; param.Value = "SeqName"; SqlDataReader reader = cmd.ExecuteReader();</code>
To get the return value of the stored procedure, you need to add a parameter with the ReturnValue direction to the SqlCommand object. This instructs the command to declare a variable and assign the return value of the stored procedure to it. The following code demonstrates the solution:
<code class="language-csharp">using (SqlConnection conn = new SqlConnection(getConnectionString())) using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = parameterStatement.getQuery(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("SeqName", "SeqNameValue"); // @ReturnVal 可以是任何名称 var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; conn.Open(); cmd.ExecuteNonQuery(); var result = returnParameter.Value; }</code>
The above is the detailed content of How to Retrieve Stored Procedure Return Values in C#?. For more information, please follow other related articles on the PHP Chinese website!