运行带有事务的脚本
本文关键字:脚本 事务 行带 运行 | 更新日期: 2023-09-27 18:08:55
我必须执行已经编写的TSQL脚本(*)。SQL文件),它没有事务。每个客户端都有大约300个脚本(大多数是不同的脚本),我编写了一个小的c#应用程序,使用sqlcmd按给定的顺序执行脚本。
脚本也包含insert'update'delete语句和ddl。
它一个接一个地运行脚本,其中一个脚本可能会失败。如果其中一个脚本失败,它将记录哪个脚本失败,并记录sqlcmd给出的错误消息。我需要在这些情况下进行回滚。我不必回滚成功运行的脚本,但我应该回滚最后一个失败的脚本。
通过回滚,我的意思是我需要恢复到最后一个脚本甚至开始之前的点。我真不知道该查什么来解决这个问题。
谢谢你的帮助。
如果我理解正确,那么这是你正在寻找的东西。只要您有一个开放的连接和开放的事务,您就可以使用它。这并不完美,但这是一个开始。
public bool GenericSP_PersistentConnection(string strStoredProcedureName, SortedList<string, string> values, SqlConnection s_persistent_conn, SqlTransaction transaction, string returnValueName)
{
try
{
if (strStoredProcedureName == "") throw new Exception(noStoredProcedure);
if (values == null) throw new Exception(noValue);
if (returnValueName == "") throw new Exception(noOutputParameterName);
//If Connection object is null, create a new on
if (s_persistent_conn == null) s_persistent_conn = new SqlConnection(GetConnectionString());
//Create command object
s_comm = new SqlCommand(strStoredProcedureName, s_persistent_conn);
s_comm.CommandType = CommandType.StoredProcedure;
s_comm.Transaction = transaction;
s_comm.CommandTimeout = 600;
s_adap = new SqlDataAdapter(s_comm);
////set up the parameters for the stored proc
foreach (var item in values)
s_comm.Parameters.AddWithValue("@" + item.Key, item.Value);
s_comm.Parameters.AddWithValue("@" + returnValueName, 0);
s_comm.Parameters["@" + returnValueName].Direction = ParameterDirection.Output;
//Excecute call to DB
s_comm.ExecuteNonQuery();
outputValue = s_comm.Parameters["@" + returnValueName].Value.ToString();
}
catch (Exception ex)
{
// If something happens, rollback the whole transaction.
transaction.Rollback();
throw ex;
}
finally
{
s_comm.Dispose();
s_adap.Dispose();
}
return true;
}
希望能有所帮助。