I am looking to Insert a row into a table and return the Identity column in c# code. I cannot seem to get the syntax quite right.
Here is the storted procedure
ALTER PROCEDURE [dbo].[sp_InsertIssue]
@Application nchar(20) = NULL ,
@Version nchar(10) = NULL ,
@CreatedBy NVARCHAR(30) = NULL ,
@AssignedTo nVARCHAR(max) = NULL ,
@Description nVARCHAR(max) = NULL ,
@UserId INT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Issue
(
Application ,
Version ,
CreatedBy ,
AssignedTo ,
Description ,
UserId
)
VALUES
(
@Application ,
@Version ,
@CreatedBy ,
@AssignedTo ,
@Description ,
@UserId
)
RETURN SCOPE_IDENTITY()
END
Here is the C# Code
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_InsertIssue ";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = m_Connection;
SqlParameter parm = new SqlParameter("@IssueId", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add("@Application", SqlDbType.VarChar).Value = p_Application;
cmd.Parameters.Add("@Version", SqlDbType.VarChar).Value = p_Version;
cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = p_CreatedBy;
cmd.Parameters.Add("@AssignedTo", SqlDbType.VarChar).Value = p_AssignedTo;
cmd.Parameters.Add("@Description", SqlDbType.VarChar).Value = p_Description;
cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = p_UserId;
var returnParameter = cmd.Parameters.Add("IssueId", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
/// send data to db
Int32 id = (int)cmd.ExecuteNonQuery();
Return -1 not the identity column