回滚批量复制

问题描述 投票:9回答:1

我有一个应用程序,通过c#中的批量复制类从我的数据库中复制。

发生异常时,我可以在sql server中回滚批量复制操作吗?

c# sql-server rollback bcp sqlbulkcopy
1个回答
13
投票

MSDN文章:Performing a Bulk Copy Operation in a Transaction 或更新的文档: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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.