SqlBulkCopy: What is the difference between passing SqlBulkCopyOptions.UseInternalTransaction and not passing it? SqlBulkCopy: What is the difference between passing SqlBulkCopyOptions.UseInternalTransaction and not passing it? windows windows

SqlBulkCopy: What is the difference between passing SqlBulkCopyOptions.UseInternalTransaction and not passing it?


If you set this option then the SQLBulkCopy class will add a

_internalTransaction = _connection.BeginTransaction();

around each batch.

But this option makes no practical difference with SQL Server as transactions by default run in auto commit mode anyway.

The only observable difference is that it performs validation that you haven't also tried to pass in an external transaction.

The following will succeed and rollback all batches

var transaction = sourceConnection.BeginTransaction();             using (SqlBulkCopy bulkCopy =    new SqlBulkCopy(sourceConnection, SqlBulkCopyOptions.Default, transaction)){    bulkCopy.BatchSize = 50;    bulkCopy.DestinationTableName = "dbo.foobar";        bulkCopy.WriteToServer(dt);}transaction.Rollback();

Passing SqlBulkCopyOptions.UseInternalTransaction fails with an error

Must not specify SqlBulkCopyOption.UseInternalTransaction and pass an external Transaction at the same time.

I wondered if it might make a difference if an SET IMPLICIT_TRANSACTIONS ON; had previously been run on the connection to turn off auto commit mode but the overload of the SqlBulkCopy constructor that takes a connection object returns an "Unexpected existing transaction." error in both cases anyway - and the overload that takes a connection string just creates a new connection.