SQL Server NOLOCK
Here is a query that returns all of the data from the Table Emp
run in query window 1
select * from Employee
I can see there is only one record that has a Salary
Let's say another user runs the query to updates the records, but it is not yet committed to the database so the records are locked.
Now, open new window and run the below query
run in query window 2
BEGIN TRAN
UPDATE Employee SET Salary = '3333'
-- ROLLBACK or COMMIT
If I run the same query from above again you will notice that it never completes, because the
UPDATE has not yet been committed.
run in query window 1
select * from Employee
Now when i Run
sp_who2 I can see that the SELECT statement is being blocked. I will need to either cancel this query or COMMIT or ROLLBACK the query in window two for this to complete. For this example I am going to cancel the SELECT query
To get around the locked records, I can use the NOLOCK hint as shown below and the query
will complete even though the query in window 2 is still running and has not been committed or
rolled back.
If you notice below the SALARY column now has 3333 for all records. This is because the UPDATE in window 2 updated these records. Even though that transaction has not been committed, since we are using the NOLOCK hint SQL Server ignores the locks and returns the data. If the UPDATE is rolled back the data will revert back to what it looked like before, so this is considered a Dirty Read.
If I rollback the UPDATE using the ROLLBACK command and rerun the SELECT query we can see the SALARY is back to what it looked like before.
-- run in query window 2
ROLLBACK
-- run in query window 1
select * from Employee(NOLOCK)
OR
SELECT * FROM Employee
No comments:
Post a Comment
Thank you for visiting my blog