Transaction isolation levels and subqueries

前端 未结 1 463
暗喜
暗喜 2021-01-06 06:09

if we have an UPDATE with a sub-SELECT, can the subquery execute concurrently or not under READ COMMITTED isolation?

In other words, is there a race condition presen

1条回答
  •  生来不讨喜
    2021-01-06 07:14

    The answer is yes, there is a race condition and two transactions may execute the subquery concurrently, leading to the same row being subsequently updated twice.

    This can be fixed by rewriting the update as

    update TEMP 
    set [state] = 'active' 
    from 
        (select top 1 * from list where [state] = 'ready' order by id) TEMP
    

    I frankly don't know why this should be different, but it is. SQL Server will now take update locks ("intent to update") when executing the subquery, preventing concurrent transactions from picking the same row.

    0 讨论(0)
提交回复
热议问题