Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback for bulk copy

I have an application that make a copy from my database by bulk copy class in c#.

Can I rollback the bulk copy action in sql server when occur an exception?

like image 961
masoud ramezani Avatar asked Feb 07 '10 07:02

masoud ramezani


People also ask

How Bulk Copy works?

The BCP (Bulk Copy Program) utility is a command line that program that bulk-copies data between a SQL instance and a data file using a special format file. The BCP utility can be used to import large numbers of rows into SQL Server or export SQL Server data into files.

What is a bulk copy?

Bulk copy from a table, view, or the result set of a Transact-SQL statement into a data file where the data is stored in the same format as the table or view. This is called a native-mode data file.

Does SqlBulkCopy use transaction?

By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of SqlBulkCopy with a connection string, or use an existing SqlConnection object without an active transaction.

What is bulk copy in C#?

So with the use of SqlBulkCopy you can send a large amount of data from any source to SQL Server database. For example you have a collection of data in XML format and you want to save this data into your database table. You can do this very easily. Today in this article we will learn how to use SqlBulkCopy in C#.


1 Answers

MSDN article: Performing a Bulk Copy Operation in a Transaction or the newer documentation: Transaction and Bulk Copy Operations | Microsoft Docs

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();
        }
    }
}
like image 56
Lachlan Roche Avatar answered Sep 21 '22 18:09

Lachlan Roche