When is it appropriate to use NOLOCK?

后端 未结 6 1869
灰色年华
灰色年华 2021-01-04 20:28

I am having timeout issues and deadlocks from time to time with some long running queries.

I\'m wondering when is it most appropriate to use NOLOCK and where?

<
6条回答
  •  轮回少年
    2021-01-04 21:10

    For a transactionally consistent view without read locks recommend enabling snapshot isolation in SQL Server.

    This is slightly different than NOLOCK in that when you read information the results always reflect a version of committed data rather than the possibility of viewing uncommited data. This provides the same locking concurrency as NOLOCK (no "read" locks) with clearer results.

    One should always keep in mind even with transactional consistency the data you then go on to display or use at the time of it being displayed can possibly be wrong or outdated anyway. I've seen too many people assume that if they use the data fast enough or if they use it within a query/transaction that it's OK. This is absurd -- it is my opinion repeatable consistency levels should never have been implemented in the first place as it just encourages bad behavior. They do not exist in Oracle.

    Personally I'm fond of disabling locking for certain non-critical data views and reports as it puts less of a load on the system and the small proboablitiy of providing slightly inaccurate results is not an issue.

    Taking advantage of repeatable read consistency levels and committing sins such as holding open transactions for user input might be a little easier on the developer in terms of initial development but will almost always lead to major road"blocks" to any hope of reasonably scaling your application.

    My view is the best approach is always to "double check" conditions that still must be true in order to apply updates to any data.

    Bad:

    UPDATE myaccount SET balance = 2000
    

    Better:

    UPDATE myaccount SET balance = balance + 2000
    

    Better still:

    UPDATE myaccount SET balance = 2000 WHERE balance = 0 AND accountstatus = 1
    

    Finally the application must check row count to make sure the expected number of rows were actually updated before presenting success feedback to the user.

提交回复
热议问题