Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using SqlCommand and scope

Tags:

c#

sqlcommand

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();
}
like image 621
Dewald Swanepoel Avatar asked Jun 08 '26 03:06

Dewald Swanepoel


1 Answers

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.

like image 82
Daniel A. White Avatar answered Jun 10 '26 17:06

Daniel A. White