When is it appropriate to use NOLOCK?

后端 未结 6 1772
灰色年华
灰色年华 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:06

    There are four transaction isolation levels in SQL Server:

    1. READ UNCOMMITTED
    2. READ COMMITTED
    3. REPEATABLE READ
    4. SERIALIZABLE

    For the tables it's applied to, NOLOCK is the equivalent of "read uncommitted". That means you can see rows from transactions that might be rolled back in the future, and many other strange results.

    Still, nolock works very well in practice. Especially for read-only queries where displaying slightly wrong data is not the end of the world, like business reports. I'd avoid it near updates or inserts, or generally anywhere near decision making code, especially if it involves invoices.

    As an alternative to nolock, consider "read committed snapshot", which is meant for databases with heavy read and less write activity. You can turn it on with:

    ALTER DATABASE YourDb SET READ_COMMITTED_SNAPSHOT ON;
    

    It is available for SQL Server 2005 and higher. This is how Oracle works by default, and it's what stackoverflow itself uses. There's even a coding horror blog entry about it.

    P.S. Long running queries and deadlocks can also indicate SQL Server is working with wrong assumptions. Check if your statistics or indexes are out of date:

    SELECT 
        object_name = Object_Name(ind.object_id),
        IndexName = ind.name,
        StatisticsDate = STATS_DATE(ind.object_id, ind.index_id)
    FROM SYS.INDEXES ind
    order by STATS_DATE(ind.object_id, ind.index_id) desc
    

    Statistics should be updated in a weekly maintenance plan.

提交回复
热议问题