Does SQLBulkCopy Upload any data upon failure?

c# sql sqlbulkcopy sql-server

Question

I am doing a sql bulk copy of data from an excel spreadsheet to a temp table, and then from a temp table to a production database.

My question is this, if for any reason the upload fails either to the temp table or to the production database, does the transaction get rolled back and no data gets imported or modified existing data?

1
3
3/4/2014 3:39:22 PM

Accepted Answer

By default SqlBulkCopy will roll back to the last batch you completed. If you have a BatchSize of 0 (the default value) it will do it all in a single batch but you may get a timeout if the batch takes too long to upload (default 30 seconds).

Another option is wrap the entire thing in a external transaction and pass it in to the constructor. This will roll back the entire insert operation on a error instead of just the last batch, this allows you to use smaller batches but still have the entire insert be a single transaction. This also lets you use that same transaction for moving data from the temporary staging table in to your live data.

Here is a snippit taken from the MSDN

using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
    destinationConnection.Open();

    using (SqlTransaction transaction = destinationConnection.BeginTransaction())
    {
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(
                   destinationConnection, SqlBulkCopyOptions.KeepIdentity,
                   transaction))
        {
            bulkCopy.BatchSize = 10;
            bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";

            // Write from the source to the destination. 
            // This should fail with a duplicate key error. 
            try
            {
                bulkCopy.WriteToServer(reader);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                transaction.Rollback();
            }
            finally
            {
                reader.Close();
            }
        }
    }
}
3
3/4/2014 4:00:26 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow