Snapshot Isolation Transaction aborted due to update conflict, but no transaction begins

非 Y 不嫁゛ 提交于 2019-12-11 11:55:41

问题


I have encountered an error on executing UPDATE statement.

Error:

Snapshot isolation transaction aborted due to update conflict. You cannot use snapshot isolation to access table 'dbo.Companies' directly or indirectly in database 'myDatabase' to update, delete, or insert the row that has been modified or deleted by another transaction. Retry the transaction or change the isolation level for the update/delete statement.

Statement:

UPDATE [ActiveSession] SET [LastActionExecutedAt] = GETDATE() WHERE [SessionID]=@id

I ran above statement through ASP.NET application.

What is curious is that the statement is executed WITHOUT transaction. The code is like below:

using(var sqlconn = new SqlConnection("connection string")
using(var sqlcmd = sqlconn.CreateCommand())
{
    sqlconn.Open();
    sqlcmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = id;

    sqlcmd.CommandText = "SELECT * FROM [ActiveSession] WHERE @id=id";
    using(var sqlreader = sqlcmd.ExecuteReader())
    {
        // read info
        reader.Close();
    }

    sqlcmd.CommandText = "UPDATE ....";
    Sqlcmd.ExecuteNonQuery();
}

I have googled and only find that the error occurs when I use SNAPSHOT isolation level transaction. BUT there is no transaction.

As described in this thread, INDEXING will help in some situations, but this does not help me.

Any idea about this error? Any help will be appreciated.

Thanks,


回答1:


As described by Damien, the update statement uses autocommit transaction.

The autocommit transaction uses the isolation level had last been declared for connection not default isolation level (see this question).

This behavior makes the update statement executed both in READ COMMITTED and SNAPSHOT isolation level, and this is why update conflict occurs.

It seems that this problem is fixed in SQL Server 2014 CU6 but I still uses 2008 R2 :(

Thanks, Damien!



来源:https://stackoverflow.com/questions/33233085/snapshot-isolation-transaction-aborted-due-to-update-conflict-but-no-transactio

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