For mass copy, go backwards.

bcp c# rollback sqlbulkcopy sql-server

Question

I have a C# program that uses the bulk copy class to create copies of my database.

When an error occurs, can I roll back the bulk copy process in SQL Server?

1
10
2/7/2010 7:15:36 AM

Accepted Answer

the more recent documentation: Operations for Transaction and Bulk Copies | Microsoft Docs, or the MSDN article: Executing a Transaction's Bulk Copy Operation

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

        try
        {
            bulkCopy.WriteToServer(reader);
            transaction.Commit();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            transaction.Rollback();
        }
        finally
        {
            reader.Close();
        }
    }
}
15
1/3/2018 7:05:06 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