Is update with nested select atomic operation?

后端 未结 1 375
春和景丽
春和景丽 2021-01-04 23:58

I need to select first (let\'s say) 10000 rows in database and return them. There may be more clients that do this operation at one time. I came up with this query:

相关标签:
1条回答
  • 2021-01-05 00:19

    SELECT places shared locks on the rows read which then can be lifted in READ COMMITED isolation mode.

    UPDATE places the update locks later promoted to exclusive locks. They are not lifted until the end of the transaction.

    You should make the locks to retain as soon as they are placed.

    You can do it by making the transaction isolation level REPEATABLE READ which will retain the shared locks until the end of the transaction and will prevent UPDATE part from locking these rows.

    Alternatively, you can rewrite your query as this:

    WITH    q AS
            (
            SELECT  TOP 10000 *
            FROM    mytable WITH (ROWLOCK, READPAST)
            WHERE   batch_id IS NULL
            ORDER BY
                    date
            )
    UPDATE  q
    SET     batch_id = @myid
    

    , which will just skip the locked rows.

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