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?
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.
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.
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.
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#.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With