SQL Server Extended Events使用2:查詢使用鎖最多的對象

來源:互聯網
上載者:User

當我們懷疑可能存在高度爭用的資源,並希望瞭解這些對象佔用多少鎖定。一旦識別鎖定頻率最高的對象,便可採取一些措施來最佳化對爭用對象的訪問。使用SQL Server Extended Events可以協助我們獲得對象使用的鎖資源。

 

--先刪除LockCounts Event Session

IF EXISTS(SELECT*
FROM sys.server_event_sessionsWHEREname='LockCounts')

DROP EVENT
sessionLockCounts ON
SERVER

GO

DECLARE @dbid int

 

SELECT @dbid =db_id('AdventureWorks')

 

DECLARE @sql nvarchar(1024)

SET @sql =
'

CREATE eventsession LockCounts ON SERVER

ADD EVENTsqlserver.lock_acquired (WHERE database_id ='+CAST(@dbidAS
nvarchar)+')

ADD TARGETpackage0.synchronous_bucketizer (

SETfiltering_event_name=''sqlserver.lock_acquired'', source_type=0,source=''resource_0'')'

 

EXEC (@sql)

GO

ALTER EVENT
sessionLockCounts ON
SERVER

STATE=start

GO

--

-- Create asimple workload that takes locks.

--

USEAdventureWorks

GO

SELECT TOP 1
* FROM HumanResources.Department

GO

-- Bucketizingtarget output is available from the

--sys.dm_xe_session_targets dynamic management view in

-- XML format.

-- The followingquery joins the bucketizing target output with

-- sys.objectsto obtain the object names.

--

SELECT name,
object_id, lock_count
FROM

(SELECT objstats.value('.','bigint')AS
lobject_id,

objstats.value('@count','bigint')
AS lock_count

FROM (

SELECT CAST(xest.target_dataAS
XML)

LockData

FROM sys.dm_xe_session_targets xest

JOIN sys.dm_xe_sessions xesONxes.address=
xest.event_session_address

JOIN sys.server_event_sessions sesONxes.name
= ses.name

WHERE xest.target_name=
'synchronous_bucketizer'ANDxes.name
= 'LockCounts'

) Locks

CROSS APPLY LockData.nodes('//BucketizerTarget/Slot')AS
T(objstats)

 )LockedObjects

INNER JOIN
sys.objects o

ONLockedObjects.lobject_id= o.object_id

WHERE o.type!=
'S' AND o.type=
'U'

ORDER BY lock_countdesc

GO

--

結果:

 

name         object_id   lock_count

-------------------------------

Department    805577908  2                                                                                                         

 

(1 row(s) affected)

 

-- Stop theevent session.

--

ALTER EVENT
SESSIONLockCounts ON
SERVER

state=stop

GO

 

--Drop the eventsession

DROP EVENT
SESSIONLockCounts ON
SERVER

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.