Home >Backend Development >C++ >How Can I Successfully Retrieve Output Parameters from a SQL Server Stored Procedure in C#?
Using stored procedure output parameters in C#
Question
Returning output parameters from a SQL Server stored procedure into a C# variable can be challenging. Despite following various recommendations, many developers still report null values or other issues.
Stored Procedure
Consider the following stored procedure usp_InsertContract
, which is designed to insert a contract number into the database and return the primary key as an output parameter:
<code class="language-sql">CREATE PROCEDURE usp_InsertContract @ContractNumber varchar(7), @NewId int OUTPUT AS BEGIN INSERT INTO [dbo].[Contracts] (ContractNumber) VALUES (@ContractNumber); Select @NewId = Id From [dbo].[Contracts] where ContractNumber = @ContractNumber; END</code>
Open database
Open the database connection using the following code:
<code class="language-csharp">pvConnectionString = "Server = Desktop-PC\SQLEXPRESS; Database = PVDatabase; User ID = sa; PASSWORD = *******; Trusted_Connection = True;"; try { pvConnection = new SqlConnection(pvConnectionString); pvConnection.Open(); } catch (Exception e) { databaseError = true; }</code>
Execute command
Execute the stored procedure using the following code:
<code class="language-csharp">pvCommand = new SqlCommand("usp_InsertContract", pvConnection); pvCommand.Transaction = pvTransaction; pvCommand.CommandType = CommandType.StoredProcedure; pvCommand.Parameters.Clear(); pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber)); SqlParameter pvNewId = new SqlParameter(); pvNewId.ParameterName = "@NewId"; pvNewId.DbType = DbType.Int32; pvNewId.Direction = ParameterDirection.Output; pvCommand.Parameters.Add(pvNewId); try { sqlRows = pvCommand.ExecuteNonQuery(); if (sqlRows > 0) Debug.Print("New Id Inserted = ", pvCommand.Parameters["@NewId"].Value.ToString()); } catch (Exception e) { Debug.Print("Insert Exception Type: {0}", e.GetType()); Debug.Print(" Message: {0}", e.Message); }</code>
Solution
Use SCOPE_IDENTITY()
to retrieve the primary key and make a few modifications to the stored procedure to solve the null value problem:
<code class="language-sql">CREATE PROCEDURE usp_InsertContract @ContractNumber varchar(7), @NewId int OUTPUT AS BEGIN INSERT INTO [dbo].[Contracts] (ContractNumber) VALUES (@ContractNumber); SELECT @NewId = SCOPE_IDENTITY(); END</code>
To use this modified stored procedure in C#, implement the following code:
<code class="language-csharp">using(SqlConnection conn = new SqlConnection(pvConnectionString)) using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertContract", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ContractNumber", SqlDbType.VarChar, 7).Value = contractNumber; cmd.Parameters.Add("@NewId", SqlDbType.Int).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value); conn.Close(); }</code>
This code successfully retrieves and prints the primary key returned from the stored procedure.
The above is the detailed content of How Can I Successfully Retrieve Output Parameters from a SQL Server Stored Procedure in C#?. For more information, please follow other related articles on the PHP Chinese website!