Sql Server locks exclusive lock shared update lock lock

Quote others. Have time to sort out the whole case.

Refers to the address: http: //www.cnblogs.com/wenjl520/archive/2012/08/24/2654412.html

Overview lock

 

I. Why introduce lock

 

Multiple users can simultaneously bring the following data inconsistency problems of concurrent database operations:

 

Lost update

A, B and two user reading the same data is modified, wherein the modification results in a destruction of the user of the results of another modification, such as booking system

 

Dirty read

A user modifies the data, the user B and then reads the data, but for some reason the user A to cancel the modification of data, data restore the original value, then B to give the generated data inconsistent with the data in the database

 

Non-repeatable read

A user reads the data, and then the user reads the data B and modifying, when inconsistency is found twice before and after re-read data when the user A

 

The main method of concurrency control is blocked, the lock operation is to prohibit a user to do certain period of time to avoid data inconsistency

 

Two locks of classification

 

There are two categories of lock points system:

 

1 from the point of view of the database system: Exclusive lock into (i.e. exclusive lock), and update the shared locks lock

 

MS-SQL Server uses the following resource lock mode.

 

Lock mode Description

Shared (S) is not used to change or update the operation data (read-only operation), such as a SELECT statement.

Update (U) for renewable resources. When prevent common form of multiple sessions in reading, locking, and then potentially updating resources deadlock.

Exclusive (X) for the data modification operations, such as INSERT, UPDATE or DELETE. The same resource at the same time ensure that no multiple updates.

Intent locks used to establish a lock hierarchy. Intention locks types: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

Schema locks used when performing the operation depends on the schema of a table. Architecture lock types: schema modification (Sch-M) and schema stability (Sch-S).

Bulk Update (BU) using the copy data to the table and specify the mass TABLOCK prompt.

 

Shared lock

Shared (S) locks allow concurrent transactions to read (SELECT) a resource. When the presence of shared (S) lock on a resource, no other transaction can modify data. Once the data has been read, immediately release the shared (S) lock on the resource, unless the transaction isolation level is set to repeatable read or higher, or use within the transaction life cycle locking hint reserve shared (S) lock.

 

Update lock

Update (U) is generally in the form of locks prevent deadlock. Transaction generally consists of a composition update mode, the transaction record is read, acquiring a shared resource (page or row) (S) of the lock, and then modify the line, which requires the lock conversion to an exclusive (X) latch. If two transactions acquired shared mode lock on the resource, and then trying to update data, a transaction attempts to lock conversion to an exclusive (X) lock. Sharing mode conversion to the exclusive lock must wait a period of time, because the lock other transactions share mode incompatible exclusive lock a transaction; lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock to be updated. Since the two transactions must be converted to an exclusive (X) latch, and wait for another transaction each transaction releases locks shared mode, thus deadlock occurs.

 

To avoid this potential deadlock problem, use the update (U) lock. Only one transaction can obtain the resource update (U) lock. If the transaction to modify the resource, the update (U) lock conversion to an exclusive (X) lock. Otherwise, lock into a shared lock.

 

Exclusive lock

Exclusive (X) lock prevents concurrent transactions access to the resource. No other transaction can modify or read exclusive (X) locks data.

 

Intent locks

Intent lock indicates that SQL Server requires some underlying resources in the hierarchy acquire a shared (S) lock or exclusive (X) lock. For example, placed in the shared table level intent lock on the intention to indicate that the transaction table shared page or row is placed (S) lock. Is provided at the table level intent lock prevents another transaction then comprises obtaining exclusive on that page table (X) lock. Intent locks improve performance because SQL Server only checks intent lock at the table level to determine if a transaction can safely acquire a lock on the table. Without having to check each row in the table locks on each page or to determine if a transaction can lock the entire table.

 

Intention locks include intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

 

Lock mode Description

Intent shared (IS) by placing the respective S locks on the resource, indicating that the transaction is intended reading portion (but not all) of the underlying resource hierarchy.

Intent exclusive (IX) by placing each of the X lock on the resource, indicating that the intention is to modify the transaction hierarchy portion (but not all) the underlying resources. IX is a superset of IS.

Shared with intent exclusive (the SIX) by placing a lock on each resource IX, it shows that the intention is to read all of the underlying transaction resource hierarchy and modify some (but not all) the underlying resources. Allow concurrent IS locks on the top-level resource. For example, placing a lock table SIX SIX lock (lock allows concurrent IS) in the above table, IX locks placed on the current page being modified (X lock is placed on the line has been modified). Although each resource within a period of time only one SIX lock to prevent other transactions updating of resources, but allows other transactions to read the underlying resource hierarchy by obtaining IS table level lock.

 

Exclusive lock: only allows the program to use locking operation, no other operations on his will not be accepted. When performing a data update command, SQL Server will automatically use an exclusive lock. When other locks exist on the object, not extending its exclusive lock.

Shared locks: shared locks resources can be read by other users, but other users can not modify it, in the implementation of Select, SQL Server will target shared locks.

Update locks: When ready to update SQL Server data, it first update of data objects as locks, so that the data can not be modified, but you can read. When SQL Server determines the data to be updated until the operation, he will automatically update lock to an exclusive lock change, when there are other locks exist on an object, it can not lock plus updates.

 

2 . From a programmer's point of view: divided into optimistic and pessimistic locking.

Optimistic locking: completely rely on the database to manage the locks work.

Pessimistic lock: Lock handle on the programmer to manage data or object.

 

MS-SQLSERVER performed simultaneously using a lock achieved between the modified user pessimistic concurrency control in a database in a plurality of

 

Three lock granularity

Lock granularity is blocked target the size of a small block size is high concurrency, but big spending, big block size is small but complicated by low overhead

 

SQL Server supports the lock granularity can be divided into rows, pages, keys, key ranges, indexes, table or database acquire locks

 

Resource Description

RID Row identifier. For individual lock row of the table.

Row lock key index. It may be used to protect key range of serial transactions.

Page  8  kilobytes (KB) of data or index page.

A group of eight adjacent extents data or index page configuration.

Table the entire table, including all data and indexes, including.

DB database.

 

Four locking the length of time

 

The length of time for the protection of the lock holding the length of time required for the level of the requested resources.

 

For shared locks to protect the read operation of the holding time depends on the transaction isolation level. When using the default READ COMMITTED transaction isolation level, only a shared lock control during the reading of the page. In the scan until you get on the next page in the scan when the release lock. If you specify HOLDLOCK tips or transaction isolation level is set to REPEATABLE READ or SERIALIZABLE, then until the end of the transaction only releases the lock.

 

According to options set for concurrent cursor scroll lock cursor can be acquired in shared mode to protect the extraction. When the need to scroll lock, until the next extraction or closed cursor (whichever occurs first) when the scroll lock release. However, if you specify HOLDLOCK, it is not released until the end of the transaction scroll lock.

 

To protect updated exclusive lock is not released until the end of the transaction.

If a connection attempt to acquire a lock, but the lock is connected with another controlled lock conflicts, it is trying to acquire the lock will block connections to:

 

The conflict lock release and connections to obtain the requested lock.

 

Connection timeout interval has expired. No time-out interval by default, but some applications to set the timeout interval to prevent an indefinite wait

 

Five custom SQL Server in the lock

 

1  treated and disposed Deadlock Deadlock priority

 

Deadlock is blocked multiple users to apply different, because the application has caught the right part of the blockade partially blocked but waiting for the other user has caused endless wait

 

SET DEADLOCK_PRIORITY may be used to control the reaction mode session in a deadlock occurs. If two processes are locked data, and until the other process releases its locks, each process to release its lock, a deadlock that is happening.

 

2  process timeout and set the lock timeout duration.

 

@@ LOCK_TIMEOUT  returns the current session lock is currently set timeout milliseconds

 

SET LOCK_TIMEOUT setting allows the application settings blocked resource statement waits the longest time. When the statement is longer than the waiting LOCK_TIMEOUT setting, the system will automatically unblocked statement, and returns the "Lock request has exceeded the timeout period" to the application  1222  Number Error Message

 

Examples

The following example is provided to lock-out period  1 , 800  msec.

SET LOCK_TIMEOUT 1800

 

3 ) Set the transaction isolation level.

 

4  ) for SELECT, INSERT, UPDATE, and DELETE statements using a table-level locking hints.

 

5 ) locking granularity configuration index

Sp_indexoption lock granularity may be used for the system stored procedure to set the index

 

Six viewing lock information

 

1  execution information EXEC SP_LOCK report on locks

2  Query Analyzer press Ctrl + 2 can see the information lock

 

Seven Precautions

 

How to avoid deadlocks

. 1  When using the transaction, the transaction processing logic minimize the early commit or rollback transactions;

2  is provided to deadlock reasonable timeout parameter, such as: 3 minutes to 10 minutes; over time, give up this operation, the process to avoid the suspension;

3  optimizer, check and avoid deadlock phenomenon;

4  . Carefully test all scripts and SP must, before it is release.

5  All SP should have error handling (by @error)

6  generally do not modify SQL SERVER affairs default level. Not recommended forcibly locked

 

How to solve the problem of database lock on the row in the table

 

Eight a few questions about locks

 

1  a row how to lock a table

 

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

 

SELECT * FROM table ROWLOCK WHERE id = 1

 

2  lock a table in the database

 

SELECT * FROM table WITH (HOLDLOCK)

 

Locking statement:

sybase:

update 表 set col1=col1 where 1=0 ;

MSSQL:

select col1 from 表 (tablockx) where 1=0 ;

oracle:

LOCK TABLE 表 IN EXCLUSIVE MODE ;

After locking others inoperable until the user unlocks the lock, unlocking the commit or rollback

 

 

A few examples to help you impress

Provided table1 (A, B, C)

A B C

a1 b1 c1

a2 b2 c2

a3 b3 c3

 

1 ) Exclusive lock

Two new connection

Execute the following statement in the first connection

begin tran

update table1

set A='aa'

where B='b2'

waitfor delay '00: 00: 30 '- wait 30 seconds

commit tran

The following statement is executed in the second connection

begin tran

select * from table1

where B='b2'

commit tran

 

If the implementation of the above two statements the same time, the select query must wait for the update is finished you can perform that is, to wait 30 seconds

 

2 ) shared lock

Execute the following statement in the first connection

begin tran

select * from table1 holdlock -holdlock man locked

where B='b2'

waitfor delay '00: 00: 30 '- wait 30 seconds

commit tran

 

The following statement is executed in the second connection

begin tran

select A,C from table1

where B='b2'

update table1

set A='aa'

where B='b2'

commit tran

 

If both statements executed simultaneously, the second connector may be performed in the select query

The update must wait for the first transaction to release a shared lock into an exclusive lock to execute after that is, to wait 30 seconds

 

3 ) Deadlock

Additional table2 (D, E)

D E

D1 E1

d2 e2

Execute the following statement in the first connection

begin tran

update table1

set A='aa'

where B='b2'

waitfor delay '00:00:30'

update table2

set D='d5'

where E='e1'

commit tran

 

The following statement is executed in the second connection

begin tran

update table2

set D='d5'

where E='e1'

waitfor delay '00:00:10'

update table1

set A='aa'

where B='b2'

commit tran

 

Meanwhile executed, the system will detect deadlocks and aborts the process

 

add another point:

Sql Server2000 support of table-level locking hints

 

HOLDLOCK hold shared locks until the entire transaction is completed, it should be released immediately when the object does not need to be locked, equal to SERIALIZABLE transaction isolation level

 

NOLOCK statement does not issue shared locks when executed, allow dirty reads, equal to READ UNCOMMITTED transaction isolation level

 

PAGLOCK use a table lock in place with a lock multiple pages

 

READPAST let sql server skip any locked rows, the enforcement branch for READ UNCOMMITTED transaction isolation level just skip RID lock, do not skip pages, regional and table locks

 

ROWLOCK mandatory use of row locks

 

TABLOCKX forced to use an exclusive table lock, the lock during the transaction to prevent any other transactions using this table

 

UPLOCK mandatory use of updated when the meter reading without a shared lock

 

Application lock:

The client application lock is a lock code generation, not the sql server itself generated lock

 

Two locks during the processing of the application

 

sp_getapplock lock application resources

 

sp_releaseapplock for the application to unlock resources

 

The difference between a locking database tables: Note

 

SELECT * FROM table WITH (HOLDLOCK) other transactions can read the table, but you can not delete update

 

SELECT * FROM other transactions table WITH (TABLOCKX) can not read the table, update, and delete

Reproduced in: https: //www.cnblogs.com/SunnyZhu/p/5726037.html

Guess you like

Origin blog.csdn.net/weixin_33907511/article/details/94672421