Why is this SqlTransaction rolling back upon closing the connection AFTER the transaction has been Committed?

97 views Asked by At

I have a series of inserts inside of a transaction, followed by a commit. If I query the database with WITH(READUNCOMMITTED) before closing the connection, it appears as expected. However, upon closing the connection, the data disappears. Why isn't the transaction actually committing?

using (SqlConnection db = new SqlConnection(connectionstring))
{
    db.Open();
    SqlTransaction transaction = db.BeginTransaction("loadRate");
    try
    {
        int id = 0;
        using (SqlDataAdapter da = new SqlDataAdapter("usp_1", db))
        {
            da.SelectCommand.Transaction = transaction;
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            id = (int)da.SelectCommand.ExecuteScalar();
        }
        int id2 = 0;
        using (SqlDataAdapter da = new SqlDataAdapter("usp_2", db))
        {
            da.SelectCommand.Transaction = transaction;
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            id2 = (int)da.SelectCommand.ExecuteScalar();
        }                    
        transaction.Commit();                    
        Console.WriteLine("Committed data");
    }
    catch (Exception insertExcept)
    {
        Console.WriteLine("Exception: " + insertExcept.Message + ".  Rolling Back");
        try
        {
            transaction.Rollback();
        }
        catch (Exception ex2)
        {                      
            Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
            Console.WriteLine("  Message: {0}", ex2.Message);
        }
    }
    finally
    {
        db.Close();
    }
}   
1

There are 1 answers

1
Jon Agnich On

Credit to @mason for pointing me in the right direction. One of the stored procedures had an uncommitted transaction within it, and while .net's Commit could not close that transaction, closing the connection rolled it back automatically. Thank you for the help!