We can add an output clause in the first sql statement.
Then use ExecuteScalar to get its id, and then use it for the second SQL statement.
Please try if this can meet your needs:
string connString = @"";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into ScoreTable OUTPUT Inserted.ID values(4,'Tom',84,54,65)", connection))
{
SqlTransaction transaction = connection.BeginTransaction();
command.Transaction = transaction;
try
{
int insertedRowID = (int)command.ExecuteScalar();
command.CommandText = "update ScoreTable set Name = @name where id = @id";
command.Parameters.Add("@name", System.Data.SqlDbType.NVarChar).Value = "UpdatedName";
command.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = insertedRowID;
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
}
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.