Data mismatch when querying with different indexes

吃可爱长大的小学妹 提交于 2019-12-04 11:26:37

You need to inspect what locks are being acquired on your table AND indexes (see link below). SQL Server is able to take separate locks on indexes as well as data. It does not lock all indexes by default.
Note: below is a guess.
Query #1 never acquires a lock on IX_ActiveTransactions_UserIdAmount, therefore query #2 is able to search the index and grab a lock on it and then wait for a row data lock to be released to complete its operation. Once this lock is released query #2 grabs it and holds it, while executing your other code.
Query #3, meantime, is still waiting for both data and index locks. Once query #2 is finished and all locks are released, ONLY then is query #3 able to use the index to do its search and therefore search up-to-date data.

In Summary:
Both query #1 and query #2 are able to search the table in parallel and return the same row. Query #2 does have to wait for query #1 to finish to get the update lock. Since query #1 does not actually modify the last row but rather insert a new one the index is not changed for the purposes of query #2.
See https://www.mssqltips.com/sqlservertip/1485/using-sql-server-indexes-to-bypass-locks/ for discussion about the inverse of your problem.

Additional Comments:
I think it would be more reliable and possibly give better performance for your purposes to lock on "Users" table (if such exists) for a specific user ID rather than rely on index locking working correctly.

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