Transaction isolation levels and subqueries

这一生的挚爱 提交于 2019-12-09 01:52:34

问题


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 present in the following:

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

In yet other words, if many connections are simulataneously executing this SQL, can we guarantee that one row is in fact updated per invocation (so long as rows in 'ready' state exist)?


回答1:


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.



来源:https://stackoverflow.com/questions/23562711/transaction-isolation-levels-and-subqueries

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