Stored procedure, inserting to the table, which has an identity column as ID
CREATE PROCEDURE InsertValue
@Value varchar(7),
@NewId int = 0 OUTPUT
AS
BEGIN
IF(NOT EXISTS(SELECT 1 FROM [Table1] WHERE Detail = @Value))
BEGIN
INSERT into [Table1] (Detail)
VALUES (@Value)
SET @NewId = SCOPE_IDENTITY();
END
END
C# code:
int newId=0;
SqlTransaction SqlTrans = null;
SqlConnection con = new SqlConnection("connection string");
con.Open();
cmd = new SqlCommand("InsertValue", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Value", "123"));
SqlParameter parId= new SqlParameter("@NewId",DbType.Int32);
parId.Value= 0;
parId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parId);
SqlTrans = con.BeginTransaction();
cmd.Transaction = SqlTrans;
try
{
cmd.ExecuteNonQuery();
// parId.Value is DBNULL
SqlTrans.Commit();
newId = Convert.ToInt32(parId.Value);
// Exception : This SqlTransaction has completed; it is no longer usable
}
catch (Exception e)
{
throw;
}
So can anyone help me with this? I want the transaction to be there in C# code, but need the value from out parameter.
If I access the value before committing the transaction, it is DBNull
and if access after committing, getting exception while casting(the value is still DBNull)
This SqlTransaction has completed; it is no longer usable.