0
Posted on Monday, September 04, 2017 by 醉·醉·鱼 and labeled under
同事瞎折腾,问了一个问题:
起100个线程连接数据库,如何保证同一个query得到100条不同的结果。

在SQL SERVER下,是可以通过这么实现的。每次读的时候,强制加一个U/X锁,这个时候,再用HINT READPAST,即可跳过已经被锁住的记录,读取下一条记录。

BEGIN TRANSACTION

SELECT TOP 1 * FROM T1 WITH(READPAST, UPDLOCK)

微软官网这么解释
READPAST
Specifies that the Database Engine not read rows that are locked by other transactions. When READPAST is specified, row-level locks are skipped but page-level locks are not skipped.

但是这里还是会发生LOCK escalate的,即key lock会升级成为page lock,或者table lock。

https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table
0
Responses to ... Skip the locked records in multiple threads/sessions

Post a Comment