Locks used in SQL Server Query statements

Source: Internet
Author: User
Tags sql server query

Some time ago, ** the DBA of the company came to our training. I talked about a lot of MYSQL optimizations. QA Stage 1: the programmer asked: "Can the with nolock in SQL statements read other locked data except for non-locked tables"

The lecturer muttered for a long time and did not explain clearly. It may be that MYSQL does not have this mechanism.) Another programmer of the company gave a very concise and clear answer.

With nolock will not be affected by other existing locks, but will not apply any locks to the table itself. The locked row data will also be read.

I personally think this sentence is clear and clear.

But the strange thing is that programmers often use this statement and don't even give it a try.

Here, we will summarize the with lock levels in other SQLSERVER.

  • With nolock: No lock
  • With holdlock: Hold a lock
  • With updlock: An Update lock is attached.
  • With xlock: mounting an exclusive lock

It should be noted that with nolock cannot be used for the update statement, such as delete insert. To put it simply, with nolock can only be used for select

For example, update dbo. test with (NOLOCK) set username = 'wokofo' -- This statement is incorrect.

Bounce: The target table of the INSERT, UPDATE, DELETE, or MERGE statement cannot use the NOLOCK or READUNCOMMITTED lock prompt.

Actual use:

 
 
  1. select top 10 * from dbo.test with(NOLOCK) 
  2. select top 10 * from dbo.test with(HOLDLOCK) 
  3. select top 10 * from dbo.test with(XLOCK) 
  4. select top 10 * from dbo.test with(UPDLOCK) 
  5.   
  6.   
  7. update dbo.test with(HOLDLOCK) set username='wokofo' 
  8. update dbo.test with(XLOCK) set username='wokofo' 
  9. update dbo.test with(UPDLOCK) set username='wokofo' 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.