0
之前介绍过通过Extended Event观察锁,这次介绍通过dm_tran_locks来观察锁。
##TranLocks SP
BEGIN TRANSACTION
DELETE TOP (1) p FROM tbl p
EXEC ##TranLocks
ROLLBACK TRANSACTION
##TranLocks SP
CREATE PROCEDURE ##TranLocks
@objectName NVARCHAR(255) = '%',
@requestMode VARCHAR(10) = '%',
@processID INT = @@SPID,
@ignoreSharedDatabaseLocks BIT = 1
AS
SELECT
DB_NAME() AS database_name,
CASE
WHEN dt1.resource_type = 'OBJECT' THEN object_name(dt1.resource_associated_entity_id, resource_database_id)
WHEN dt1.resource_type IN('KEY', 'PAGE') THEN object_name(pa1.object_id)
ELSE dt1.resource_description
END AS object_name,
in1.name AS index_name,
pa1.partition_number,
dt1.resource_type,
dt1.request_mode,
COUNT(*) AS locks,
dt1.request_owner_id,
dt1.request_session_id
FROM
sys.dm_tran_locks dt1
LEFT OUTER JOIN sys.partitions pa1 ON(dt1.resource_associated_entity_id = pa1.hobt_id)
LEFT OUTER JOIN sys.indexes in1 ON(pa1.object_id = in1.object_id AND pa1.index_id = in1.index_id)
WHERE
(request_session_id = @processID OR @processID = 0)
AND request_mode LIKE @requestMode
AND(NOT(dt1.resource_type = 'DATABASE' AND dt1.request_mode = 'S') OR @ignoreSharedDatabaseLocks = 0)
AND dt1.resource_database_id = DB_ID()
AND
CASE
WHEN dt1.resource_type = 'OBJECT' THEN object_name(dt1.resource_associated_entity_id, resource_database_id)
WHEN dt1.resource_type IN('KEY', 'PAGE') THEN object_name(pa1.object_id)
ELSE dt1.resource_description
END LIKE @objectName
GROUP BY
dt1.resource_type,
CASE
WHEN dt1.resource_type = 'OBJECT' THEN object_name(dt1.resource_associated_entity_id, resource_database_id)
WHEN dt1.resource_type IN('KEY', 'PAGE') THEN object_name(pa1.object_id)
ELSE dt1.resource_description
END,
in1.name,
pa1.partition_number,
dt1.request_mode,
dt1.request_session_id,
dt1.request_owner_id
ORDER BY database_name, object_name, index_name, partition_number, request_mode, locks;
GO
Post a Comment