SQL Scripts from dotnet with transactions

旧时模样 提交于 2020-01-02 12:17:10

问题


I have been trying to execute sql scripts from dotnet (C#) but the sql scripts could contain GO statements and I would like to be able to wrap the collection of scripts in a transaction.

I found this question and the accepted answer got me going for handling the GO statements, but if I use a BeginTransaction it throws a InvalidOperationException at the "new ServerConnection" line.

SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction(transactionName);
ServerConnection serverConnection = new ServerConnection(connection);

I am running this against a SQL 2005 server.


回答1:


I found a way, after trying several combinations, the simplest one worked...

Well this is assuming you are using a TransactionScope object

using (
    var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
                                                    {
                                                        IsolationLevel =
                                                            IsolationLevel.ReadCommitted,
                                                        Timeout = TimeSpan.FromMinutes(300)
                                                    }))
{
    sqlServerInstance.ConnectionContext.SqlExecutionModes = SqlExecutionModes.ExecuteAndCaptureSql;
    sqlServerInstance.ConnectionContext.StatementTimeout = int.MaxValue;

    //This line makes the MAGIC happen =)
    sqlServerInstance.ConnectionContext.SqlConnectionObject.EnlistTransaction(Transaction.Current);
    sqlServerInstance.ConnectionContext.ExecuteNonQuery(scriptContent);
}



回答2:


Try using the BeginTransaction and CommitTransaction methods on the ServerConnection instance instead. I use this without any problems.




回答3:


Try starting the transaction after you've attached the ServerConnection to the SqlConnection's settings.

Also, what are you using ServerConnection for that you can't do from SqlConnection?



来源:https://stackoverflow.com/questions/1041393/sql-scripts-from-dotnet-with-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!