Batch Update/insert in using SQLCommand in C#

SqlCommand command = new SqlCommand();
// Set connection, etc.
for(int i=0; i< items.length; i++) {
    command.CommandText += string.Format("update mytable set s_id=@s_id{0} where id = @id{0};", i);
    command.Parameters.Add("@s_id" + i, items[i].SId);
    command.Parameters.Add("@id" + i, items[i].Id);
}
command.ExecuteNonQuery();

Edited Warning: this answer, albeit partially correct, does not address the issue asked, in fact ExecuteNonQuery submits the workload to the database (this can be proved by writing an incorrect query: the exception is thrown on ExecuteNonQuery and not on Commit).

Only to append all CommandTexts to one big batch command is not as useful as it seems to be.

The main benefit of prepared statements in C# is, that the workload in the database is done while creating the command. Not, when you execute it [e.g. with ExecuteNonQuery() - which executes the command only if you don't have a transaction object created].

To avoid this and to create the workload in the database only once for all your statements, it's significant better to create a Transaction object and to commit this transaction. Then all commands will be executed without any more workload in the database.

This would be a better approach:

// Try to create the Command as early as possible with a valid Connection object
string commandString = "UPDATE Mytable SET s_id=@s_id where id = @id;";
var command = new SqlCommand(commandString, connection);

// Then define a Transaction object with your Connection
var transaction = connection.BeginTransaction();
command.Transaction = transaction;

// Now iterate through your array
for(int i=0; i<array.Length; i++)
{
  command.Parameters.Add("@s_id", SqlDbType.YourType).Value = items[i].SId;
  command.Parameters.Add("@id", SqlDbType.YourType).Value = items[i].Id;
  command.ExecuteNonQuery(); // Not executed at this point
}

// And now execute it with the possibility to rollback all commands when it fails
try {  transaction.Commit(); } // Here the execution is committed to the DB
catch (Exception)
{
  transaction.Rollback();
  throw;
}

SqlBulkCopy is rather handy for situations such as these.

Tags:

C#

Asp.Net