Could anyone tell me perhaps whether there is a good reason to use one of the following two blocks of code rather than the other?
using (SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction)
{
using (SqlCommand mySqlCmd =
new SqlCommand("First of many SQL statements here", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MyFirstParm", SqlDbType.Int).Value = myFirstVal;
mySqlCmd.ExecuteNonQuery();
}
using (SqlCommand mySqlCmd =
new SqlCommand("Second of many SQL statements here", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MySecondParm", SqlDbType.Int).Value = mySecondVal;
mySqlCmd.ExecuteNonQuery();
}
.
.
.
sqlTransaction.Commit();
}
vs.
using (SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction)
{
using (SqlCommand mySqlCmd = new SqlCommand("", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MyFirstParm", SqlDbType.Int).Value = myFirstVal;
mySqlCmd.Parameters.Add("@MySecondParm", SqlDbType.Int).Value = mySecondVal;
mySqlCmd.CommandText = "First of many SQL statements here";
mySqlCmd.ExecuteNonQuery();
mySqlCmd.CommandText = "Second of many SQL statements here";
mySqlCmd.ExecuteNonQuery();
.
.
.
}
sqlTransaction.Commit();
}
I would go with 1 since you are having a fresh set of parameters for each SqlCommand.
I would also suggest moving these into separate methods or even doing it as a sproc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With