Home >Backend Development >C++ >How Can I Retrieve Output Parameters, Including SCOPE_IDENTITY(), from SQL Server Stored Procedures in C#?
Successfully retrieving output parameter values, particularly the primary key using SCOPE_IDENTITY()
, from SQL Server stored procedures in C# can be tricky. This article addresses common difficulties and provides a practical solution.
The usp_InsertContract
stored procedure demonstrates the process. It inserts a record into the Contracts
table and returns the newly generated primary key (the Id
column) via the @NewId
output parameter. The updated procedure uses SCOPE_IDENTITY()
for accurate primary key retrieval:
<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>
The C# code snippet below shows how to handle the output parameter:
<code class="language-csharp">SqlParameter pvNewId = new SqlParameter(); pvNewId.ParameterName = "@NewId"; pvNewId.DbType = DbType.Int32; pvNewId.Direction = ParameterDirection.Output; // ... (Add pvNewId to the SqlCommand object 'cmd') ... // Execute the stored procedure cmd.ExecuteNonQuery(); // Retrieve the output value int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value);</code>
If you're encountering issues, verify the following:
Contracts
table includes an identity column (auto-incrementing primary key).SCOPE_IDENTITY()
within the stored procedure to retrieve the last inserted identity value.SqlParameter
object (pvNewId
) is correctly added to the SqlCommand
object (cmd
) and that its properties (ParameterName
, DbType
, Direction
) are accurately set.By addressing these points, you can effectively retrieve output parameters, including those generated by SCOPE_IDENTITY()
, from your SQL Server stored procedures within your C# applications.
The above is the detailed content of How Can I Retrieve Output Parameters, Including SCOPE_IDENTITY(), from SQL Server Stored Procedures in C#?. For more information, please follow other related articles on the PHP Chinese website!