SQL Server transactions and locks

1. Affairs

1.1 ACID of transaction

  • Atomicity: The operations within a transaction have either all succeeded or all failed
  • Consistency: to ensure the consistency of the transaction, the data remains consistent before and after the transaction is successful
  • Isolation: no interference between transaction and transaction
  • Persistence: After the transaction is committed, the data will not be lost

1.2 Transaction control

1. Explicit transaction

  • begin transaction: explicitly start a transaction
  • rollback transaction: explicitly rollback a transaction
  • commit transaction: explicitly commit a transaction

2. Implicit transaction

Implicit submission needs to enable the implicil_transactions parameter of the database (set implicil_transactions on is enabled). After the implicit transaction is turned on, a transaction is opened by default when the first statement is executed, and the commit and rollback need to be explicitly executed to complete the transaction.

3. Automatically commit the transaction

Each individual statement is a transaction

Second, the lock

2.1 Lock granularity

  • Row lock: The minimum granularity lock of the database, which is only locked for a certain row level (RID/KEY)
  • Page lock: lock for a certain data page. In the T-SQL statement, if the query uses page lock, the same type of row lock will no longer be used; if the same type of row lock is used, the same type of row lock will not be used again Page lock (PAGE)
  • Table lock: lock the entire table (Obgect)
  • Database lock: Setting the database as read-only or preventing others from deleting the database when querying data will add a lock resource (DATABASE) at the database level

2.2 Lock mode

Common lock modes

  • Shared lock (S lock): Before searching for data, obtain the shared lock of the record. The shared locks are compatible to improve the read and read concurrency. Under the SQL Server default isolation level, the shared lock will be released after use, and will not be released until the transaction is committed/rolled back.
  • Exclusive lock (X lock): Before updating the data, obtain the record lock (exclusive lock) to prevent other transactions from updating the record.
  • Update lock (U lock): occurs in the operation of updating data. The update lock is used to find data. When the scanned data is not the updated record, it is the same as the S lock. It is released after use; if the scanned data is needed When updating the record, upgrade the U lock to X lock and perform the update operation.
  • Intentional lock (IU lock): Intentional locks are divided into shared intentional locks (IS locks), exclusive intentional locks (IX), intentional update locks (IU), shared intentional exclusive locks (SIX), shared intentional update locks (SIU), Update the intention exclusive lock (UIX), which occurs before the lower-granularity lock resource acquisition.
  • Architecture lock (Sch-S/M): The query does not prevent the architecture modification and needs to obtain the Sch-S lock, and the Sch-M lock is obtained when the DDL operation is performed to adjust the architecture.

2.3 Lock compatibility

- IS S U IX SIX X
IS Yes Yes Yes Yes Yes no
S Yes Yes Yes no no no
U Yes Yes no no no no
IX Yes no no Yes no no
SIX Yes no no no no no
X no no no no no no

2.4 Lock related parameters

  • lock_timeout

This parameter defaults to -1, which means that there is no lock timeout waiting limit. The unit is milliseconds.

-- 查看当前锁超时的全局设置
select @@LOCK_TIMEOUT

-- 会话层面设置锁超时
set LOCK_TIMEOUT  5000      //5秒锁超时

2.5 Deadlock

1. What is a deadlock

Deadlock refers to a phenomenon in which two transactions are waiting for each other due to resource contention during the execution process. The main reason for this phenomenon is that the order in which the two transactions are locked is inconsistent, causing each transaction to request each other to hold each other. Some resources, resulting in a deadlock closed loop. Generally, a deadlock in the database will give priority to rollback of transactions with smaller weights.

2. How to avoid deadlock

  • Avoid big/long transactions and commit the transactions in time
  • Effectively reduce the lock range through the index

2.6 Lock monitoring

1. Detailed version of each session lock blocking status query

SELECT  
der.[session_id], 
[request_id], 
percent_complete, 
estimated_completion_time/1000/60, 
con.[client_net_address], 
con.local_net_address, 
[start_time] AS '开始时间', 
[status] AS '状态', 
[command] AS '命令', 
dest.[text] AS 'sql语句', 
DB_NAME([database_id]) AS '数据库名', 
[blocking_session_id] AS '正在阻塞其他会话的会话ID', 
[wait_type] AS '等待资源类型', 
[wait_time] AS '等待时间', 
[wait_resource] AS '等待的资源', 
[reads] AS '物理读次数', 
[writes] AS '写次数', 
[logical_reads] AS '逻辑读次数', 
[row_count] AS '返回结果行数', 
[cpu_time], 
percent_complete 
FROM sys.[dm_exec_requests] AS der 
outer APPLY 
sys.[dm_exec_sql_text](der.[sql_handle]) AS dest 
left join sys.dm_exec_connections con 
on der.session_id=con.session_id 
WHERE der.[session_id]>50 AND 
DB_NAME(der.[database_id])='db1' 
ORDER BY [reads] DESC

2. The simple version of each session lock blocking status query

SELECT spid,kpid,blocked ,waittime AS 'waitms', lastwaittype, DB_NAME(dbid),  waitresource, open_tran,hostname,[program_name],hostprocess,loginame, [status]
FROM sys.sysprocesses WITH(NOLOCK) 
WHERE    kpid>0  AND  [status]<>'sleeping'  AND spid>50
ORDER BY waittime DESC

3. Inquiry about the lock blocking situation in the minimalist version

select blocking_session_id, wait_duration_ms, session_id from 
sys.dm_os_waiting_tasks
where blocking_session_id is not null

dbcc INPUTBUFFER(${session_id})         //查看具体会话执行SQL情况

4. Lock waiting for each session to hold lock resource information view

SELECT  k.request_session_id,k.resource_type,k.request_status,k.request_mode,k.resource_description,
OBJECT_NAME( p.object_id) as objectName,p.index_id FROM SYS.dm_tran_locks k LEFT JOIN SYS.PARTITIONS p
ON k.resource_associated_entity_id=p.hobt_id
ORDER BY request_session_id,resource_type

Guess you like

Origin blog.csdn.net/weixin_37692493/article/details/107372501