谁能解释一下在查询中使用with (nolock)的含义,什么时候应该/不应该使用它?

例如,如果你有一个银行应用程序,有很高的事务率,在某些表中有很多数据,在什么类型的查询中nolock是可以的?在某些情况下,你是否应该总是使用它/永远不要使用它?


当前回答

不幸的是,这不仅仅是读取未提交的数据。在后台,您可能会读两次页面(在页面分割的情况下),或者您可能会完全错过这些页面。所以你的结果可能是严重扭曲的。

看看Itzik Ben-Gan的文章。以下是节选:

" With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice. "

其他回答

您可以在仅读取数据时使用它,并且并不真正关心是否可能返回尚未提交的数据。

它可以在读取操作上更快,但我不能确切地说快多少。

一般来说,我建议不要使用它——读取未提交的数据最多可能会有点混乱。

我的2分——当你需要生成报告时,使用WITH (NOLOCK)是有意义的。在这一点上,数据不会有太大的变化&你不会想要锁定这些记录。

WITH (NOLOCK)相当于使用READ uncommitted作为事务隔离级别。因此,您可能会读取一个未提交的行,该行随后会被回滚,即从未进入数据库的数据。因此,虽然它可以防止读取被其他操作死锁,但也存在风险。在具有高交易率的银行应用程序中,它可能不是您试图用它解决的任何问题的正确解决方案。

另一种通常可以接受的情况是在报告数据库中,其中的数据可能已经老化,不会发生写入操作。但是,在这种情况下,管理员应该通过更改默认隔离级别在数据库或表级别设置该选项。

在一般情况下:当你非常确定可以读取旧数据时,你可以使用它。重要的是要记住这很容易出错。例如,即使在编写查询时没有问题,但您确定将来数据库中不会有什么变化使这些更新变得更重要吗?

我还想说的是,在银行应用程序或库存应用程序中,这可能不是一个好主意。

不幸的是,这不仅仅是读取未提交的数据。在后台,您可能会读两次页面(在页面分割的情况下),或者您可能会完全错过这些页面。所以你的结果可能是严重扭曲的。

看看Itzik Ben-Gan的文章。以下是节选:

" With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice. "