2

Having the following code what would happen if I return from method without calling Commit() on the transaction object?

var transaction = connection.BeginTransaction();

try
{
    int val;

    var myCommand = new SqlCommand(
        @"SELECT ......",
        connection, transaction);

    using (var reader = myCommand.ExecuteReader())
    {
        if (reader.Read() && !reader.IsDBNull(0))
        {
            if (int.TryParse(reader.GetString(0), out val))
            {
                return val; // <--- this code executes
            }
        }
    }

    transaction.Commit() // <--- this code never executes
}
catch (Exception ex)
{                    

    // Rollback the transaction.
}
bigb055
  • 198
  • 3
  • 14
  • 1
    Although BEGIN TRANSACTION starts a local transaction, it is not recorded in the transaction log until the application subsequently performs an action that must be recorded in the log, such as executing an INSERT, UPDATE, or DELETE statement. An application can perform actions such as acquiring locks to protect the transaction isolation level of SELECT statements, but nothing is recorded in the log until the application performs a modification action. https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql?view=sql-server-2017 – Roy Jan 22 '19 at 15:13

0 Answers0