Using WITH(NOLOCK) to increase performance

天大地大妈咪最大 提交于 2019-12-24 12:51:57

问题


I have seen developers using WITH(nolock) in the query, is there any disadvantage of it? Also, what is the default mode of execution of query? My database do not have any index.

Is there any other way to increase database select statement performance?


回答1:


The common misconception with nolock is that that it places no locks on the database whilst executing. Technically it does issues a schema-stability (sch-s) lock, so the 'no' part of the lock relates to the data side of the query.

Most of the time that I see this, it is a premature optimization by a developer because they have heard it makes the query faster.

Unless you have instrumented proof and validity in accepting a dirty read (and potentially reading the same row twice) then it should not be used - it definately should not be the default approach to queries, but an exception to the rule when it can be shown that it is required.




回答2:


There are numerous articles on this on the net. The main risk is that with NOLOCK you can read uncomitted data from the table (dirty reads). See, for example, http://msdn.microsoft.com/en-us/library/aa259216(v=sql.80).aspx or http://www.techrepublic.com/article/using-nolock-and-readpast-table-hints-in-sql-server/6185492




回答3:


NOLOCK can be highly useful when you are reading old data from a frequently used table. Consider the following example,

You have a stored procedure to access data of inactive projects. You don't want this stored procedure to lock the frequently used Projects table while reading old data.

NOLOCK is also useful when dirty reads are not a problem and data is not frequently modified such as in the following cases,

Reading list of countries, currencies, etc... from a database to show in the form. Here the data remains unchanged and a dirty read will not cause a big problem as it will occur very rarely.

However starting with SQL server 2005 the benefits of NOLOCK is very little due to row versioning.



来源:https://stackoverflow.com/questions/5376222/using-withnolock-to-increase-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!