I am creating a view on a MS SQL Server. I have not had much exposure to MS SQL and am not real familiar with the NO LOCK hint. I understand what it does, but I don't know if I need to use it in my situation. I have been asked if I should include it and I don't know.
Do I need to add NO HINT after all the queries I am using to create my view? Or will that have any affect on the user querying the view itself? Should the USER add the NO LOCK to the query against the VIEW?
Any guidance on the best approach and any clarification is appreciated!
The WITH (NOLOCK) table hint is used to override the default transaction isolation level of the table or the tables within the view in a specific query, by allowing the user to retrieve the data without being affected by the locks, on the requested data, due to another process that is changing it.
The NOLOCK hint allows SQL to read data from tables by ignoring any locks and therefore not get blocked by other processes. This can improve query performance by removing the blocks, but introduces the possibility of dirty reads. Read further to better understand the use of NOLOCK.
The benefits of querying data using the NOLOCK table hint is that it requires less memory and prevents deadlocks from occurring with any other queries that may be reading similar data.
According to this, a NOLOCK query issues a Sch-S lock and thus will only block things that, like DDL and re-index jobs. However, we're seeing DML read/write being blocked also, causing our whole app to go down.
I will answer your question first.
It is better to have the NOLOCK hint on the view from outside instead of on the tables in the view.
For example
select * from vwTest with (nolock)
or
set transaction isolation level read uncommitted
select * from vwTest
Doing it this way you as the creator is catering for a wider user base who may or may not be as experienced at SQL as yourself. By not encapsulating NOLOCK hints in the view encourages other developers to really think about how they would like to retrieve the data in a safe and efficient manner.
Now more info on NOLOCK. It is a nice trick if you are 100% sure the underlying data is no longer changing, a good example is when a ETL system finishes loading data for the day. It is also handy in a read-only reporting system where again you are sure there is no data movement between report runs.
Otherwise, it is not a recommended hint to use in your system. It does more harm than good if you don't really understand the implications.
Please refer to the following links for the damages NOLOCK can cause: Previously committed rows might be missed if NOLOCK hint is used
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With