您的位置:首页 > 数据库

T-SQL Part V: Locks

2016-05-30 16:50 351 查看
写SQL最常见的问题就是Dead Lock了。本篇简单介绍入门级别的Lock使用和排查。

首先来看MSDN上的官方文档(https://technet.microsoft.com/en-us/library/jj856598(v=sql.110).aspx)。

摘要一下,SQL Server可以进行Lock的Resource:

ResourceDescription
RIDA row identifier used to lock a single row within a heap.
KEYA row lock within an index used to protect key ranges in serializable transactions.
PAGEAn 8-kilobyte (KB) page in a database, such as data or index pages.
EXTENTA contiguous group of eight pages, such as data or index pages.
HoBTA heap or B-tree. A lock protecting a B-tree (index) or the heap data pages in a table that does not have a clustered index.
TABLEThe entire table, including all data and indexes.
FILEA database file.
APPLICATIONAn application-specified resource.
METADATAMetadata locks.
ALLOCATION_UNITAn allocation unit.
DATABASEThe entire database.
Lock的类型:

Lock modeDescription
Shared (S)Used for read operations that do not change or update data, such as a SELECT statement.
Update (U)Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.
Exclusive (X)Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.
IntentUsed to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
SchemaUsed when an operation dependent on the schema of a table is executing. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Bulk Update (BU)Used when bulk copying data into a table and the TABLOCK hint is specified.
Key-rangeProtects the range of rows read by a query when using the serializable transaction isolation level. Ensures that other transactions cannot insert rows that would qualify for the queries of the serializable transaction if the queries were run again.
T-SQL中,使用Lock最简单的方法当然是SELECT ... FOR UPDATE,选中对应的ROW进行Lock以便Update。

进行Lock排查,可以通过以下方式进行查看当前Lock的状态:

exec sp_lock; 这是最原始的方式,dump所有Lock相关的信息。
select cmd,* from sys.sysprocesseswhere blocked > 0通过查看当前sysprocesses的方式来抉择那些process被blocked。配合上exec sp_who2和kill,分别用来查看process的信息和终止指定的process。

select * from sys.dm_tran_locks; Dynamic View dm_trans_locks返回当前系统中的locks。Dynamic Views and Functions请参阅:https://msdn.microsoft.com/en-us/library/ms188754.aspx

是为之记。

Alva Chien

2016.5.30
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息