views:

50

answers:

1

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?

+3  A: 

MSDN article Performing a Bulk Copy Operation in a Transaction - http://msdn.microsoft.com/en-us/library/tchktcdk%28VS.80%29.aspx see under Using Existing Transactions.

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();
        }
    }
}
Lachlan Roche
thanks Lachlan.
masoud ramezani