简体   繁体   中英

Run scripts with transaction

I have to execute already written TSQL scripts (*.sql files), that doesn't have transacion. I have around 300 scripts for each client (mostly different scripts), and I wrote a little C# application that uses sqlcmd to execute scripts in the given order.

The scripts contain insert\\update\\delete statements and ddl too.

It runs the scripts one-by-one, and there is a possibility that one of the scripts fails. If one of the scripts fails, it logs which one did, and logs the error message that the sqlcmd gives too. I need to rollback at these situations. I don't have to rollback the scripts that successfully ran, but I should roll back the last one that failed.

By rollback I mean I need to restore to the point before the last script even started. I don't really know what should I look up to solve this.

Thank you for any help.

If I understood right then this is something you are looking for. As long as you have an open connection and open transaction, you can use this. It is not perfect, but it is a start.

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;
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM