SQL server lock type and usage (reprint)

I. Why introduce lock

multiple users to simultaneously bring the following data inconsistency issue concurrent database operations:

lost update
A, B two users read the same data and make changes, which modify the results of a user break another result of the changes, such as booking system

dirty read
a modified user data, and user B then reads the data, but for some reason the user a to cancel the modification of data, data restore the original value, the data B obtained at this time and generates data in the database inconsistent

non Repeatable read
a read user data, the user then reads the data B and modifying, when the two are inconsistent values before and after the user found the re-read data a

primary concurrency control method is block lock that prevents users do certain operations in a period of time to avoid data inconsistency

two free lock

locks category includes two sub-method:

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

MS-SQL Server uses the following resource lock mode.

Lock mode is described
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, it immediately releases 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. It 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 is described
intent share (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, show 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 between users simultaneously performed using a modified lock in a database implemented pessimistic concurrency control in a plurality of

three lock granularity
lock granularity size of the target is blocked, the blocking of small particle size high concurrency, but the overhead is large block size concurrency low overhead small but

supported by SQL Server 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 length of the guard locks held for the 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 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 locks in SQL Server custom

1 handle deadlocks and priority setting deadlock

deadlock is blocking multiple users to apply different, because the applicant but all have the right to block part of the waiting section block other users have caused endless wait

can be used to control the reaction SET DEADLOCK_PRIORITY way session when 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 and the process to set the lock timeout 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 to the application program "has exceeded the lock request timeout period" error message 1222

exemplary
embodiment lock timeout period is set at 1,800 milliseconds.
LOCK_TIMEOUT 1800 the SET

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
can be used to sp_indexoption system stored procedure provided for indexing the locking granularity

six view information lock

a lock execution EXEC SP_LOCK report information
2 Query Analyzer press Ctrl + 2 can see the information lock

precautions seven

how to avoid deadlocks
when using a transaction, the transaction processing logic minimize the early commit or rollback transactions;
2 deadlock timeout parameter set to a reasonable range, such as: 3 minutes to 10 minutes; over time, waiver of this operation, to avoid the process of suspension;
3 optimizer, check and avoid deadlock phenomenon;
4. carefully test all scripts and SP must, before it is release.
5 SP should have all the error handling (by @error)
6 levels generally do not modify the default SQL SERVER transactions. I do not recommend locking force

to solve the problem of how to lock the database rows in the table

Eight issues related to several locks

1 how to lock a particular row of the table

TRANSACTION the ISOLATION the LEVEL the READ UNCOMMITTED the SET

the SELECT * the WHERE ID = ROWLOCK the FROM. 1 Table

2 a locked database table

SELECT * FROM table WITH (HOLDLOCK)

lock statement:
Sybase:
Update table WHERE col1 = col1. 1 SET = 0;
MSSQL:
SELECT col1 from table (TABLOCKX) WHERE. 1 = 0;
Oracle:
the lOCK tABLE tABLE IN EXCLUSIVE MODE;
the others lock inoperable until the user unlocks the lock, unlocking commit or rollback


few examples help you impress
disposed table1 (A, B, C)
the ABC
A1 C1 B1
A2 B2 C2
A3 B3 C3

. 1) exclusive lock on
the new connection two
the following statement in the first connection
the begin Tran
Update table1
SET a = 'AA'
WHERE = B 'B2'
WAITFOR Delay '00: 00: 30 '- wait 30 seconds
commit tran
following statement in the second connection
Tran the begin
select * from table1
WHERE = B 'B2'
the commit Tran

when simultaneously executing the two statements, the select query must wait to perform the update is finished i.e. to wait 30 seconds

2) share lock
the following statement in the first connection
Tran the begin
SELECT * from the holdlock -holdlock human lock table1
WHERE = B 'B2'
WAITFOR Delay '00: 00: 30 '- wait 30 seconds
commit tran

following statement in the second connection
the begin Tran
SELECT A, from C table1
WHERE = B 'B2'
update table1
SET a = 'AA'
WHERE = B 'B2'
the commit Tran

when simultaneously executing the two statements, the second connection select query may perform
the update transaction must wait for the first shared lock is released into the exclusive lock to execute that is, to wait 30 seconds

3) deadlock
additional table2 (D,E)
DE
D1 E1
D2 E2
executing the following statement in the first connection
the begin Tran
Update table1
A = SET 'AA'
WHERE = B 'B2'
WAITFOR Delay '00: 00: 30 '
Update Table2
SET D =' d5 of '
WHERE E =' E1 '
the commit Tran

following statement in the second connection
the begin Tran
Update Table2
D = SET 'd5 of'
WHERE E = 'E1'
WAITFOR Delay '00: 00: 10 '
Update table1
SET A =' AA '
WHERE = B' B2 '
the commit Tran

performed simultaneously, the system will detect a deadlock, and abort the process

add this:
Sql Server2000 support of table-level locking hints

HOLDLOCK hold shared locks until the entire transaction is completed, 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 with multiple pages use a table lock locks in place

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 , and a region table lock

ROWLOCK row locks enforce

TABLOCKX forced to use exclusive table-level lock that prevents any other transactions during a transaction using this table

UPLOCK forces the meter reading using update instead of a shared lock

application lock:
application lock is the client code generation of locks, rather than sql server the lock itself generates

two during the processing of the application lock

sp_getapplock lock application resources

sp_releaseapplock unlock resources for the application

Note: locking a table in the database difference

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

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

Guess you like

Origin www.cnblogs.com/lichenghong/p/12449542.html