T-SQL Part V: Locks

寫SQL最常見的問題就是Dead Lock了。本篇簡單介紹入門級別的Lock使用和排查。

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

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

Resource Description
RID A row identifier used to lock a single row within a heap.
KEY A row lock within an index used to protect key ranges in serializable transactions.
PAGE An 8-kilobyte (KB) page in a database, such as data or index pages.
EXTENT A contiguous group of eight pages, such as data or index pages.
HoBT A 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.
TABLE The entire table, including all data and indexes.
FILE A database file.
APPLICATION An application-specified resource.
METADATA Metadata locks.
ALLOCATION_UNIT An allocation unit.
DATABASE The entire database.

Lock的類型:

Lock mode Description
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.
Intent Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
Schema Used 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-range Protects 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章