开发者

How to use SqlBulkCopy with SMO and transactions

I'm trying to create a table using SMO, and further use the SqlBulkCopy object to inject a bunch of data into that table. I can do this without using a transaction like this:-

Server server = new Server(new ServerConnection(new SqlConnection(connectionString)));
var database = server.Databases["MyDatabase"];

using (SqlConnection connection = server.Connection开发者_C百科Context.SqlConnectionObject)
{
    try
    {
        connection.Open();
        Table table = new Table(database, "MyNewTable");
        // --- Create the table and its columns --- //

        SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection);
        sqlBulkCopy.DestinationTableName = "MyNewTable";
        sqlBulkCopy.WriteToServer(dataTable);
    }
    catch (Exception)
    {
        throw;
    }
}

Basically I want to perform the above using a SqlTransaction object and committing it when the operation has been completed (Or rolling it back if it fails). Can anyone help?


2 Things -

A - The SQLBulkCopy method is already transaction based by default. That means the copy itself is encapsulated in a transaction and works for fails as a unit.

B - The ServerConnection object has methods for StartTransaction, CommitTransaction, RollbackTransaction.

You should be able to use those methods in your code above, but I suspect if there is an issue with the table creation your try/catch will handle that appropriately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜