From: https://www.cnblogs.com/K-R-/p/18431639
簡單點的處理方法:
1、查詢死鎖的表
select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName from sys.dm_tran_locks where resource_type='OBJECT'
2、解鎖
declare @spid int Set @spid = 79 --鎖表程序 declare @sql varchar(1000) set @sql='kill '+cast(@spid as varchar) exec(@sql)
專業點的處理方法:
1.查詢死鎖的表:
SELECT request_session_id spid, OBJECT_NAME( resource_associated_entity_id ) tableName FROM sys.dm_tran_locks WHERE resource_type = 'OBJECT'
2.分析被鎖死的原因:
select t1.resource_type [資源鎖定型別] , DB_NAME(resource_database_id) as 資料庫名 , t1.resource_associated_entity_id 鎖定物件 , t1.request_mode as 等待者請求的鎖定模式 , t1.request_session_id 等待者SID , t2.wait_duration_ms 等待時間 , (select TEXT from sys.dm_exec_requests r cross apply sys.dm_exec_sql_text(r.sql_handle) where r.session_id = t1.request_session_id) as 等待者要執行的SQL , t2.blocking_session_id [鎖定者SID] , (select TEXT from sys.sysprocesses p cross apply sys.dm_exec_sql_text(p.sql_handle) where p.spid = t2.blocking_session_id ) 鎖定者執行語句 from sys.dm_tran_locks t1, sys.dm_os_waiting_tasks t2 where t1.lock_owner_address = t2.resource_address
3.解鎖:
create Proc Sp_KillAllProcessInDB @DbName VarChar(100) as if db_id(@DbName) = Null begin Print 'DataBase dose not Exist' end else Begin Declare @spId Varchar(30) DECLARE TmpCursor CURSOR FOR Select 'Kill ' + convert(Varchar, spid) as spId from master..SysProcesses where db_Name(dbID) = @DbName and spId <> @@SpId and dbID <> 0 OPEN TmpCursor FETCH NEXT FROM TmpCursor INTO @spId WHILE @@FETCH_STATUS = 0 BEGIN Exec (@spId) FETCH NEXT FROM TmpCursor INTO @spId END CLOSE TmpCursor DEALLOCATE TmpCursor end
4、查詢SQL佔用資源情況:
SELECT TOP 20 total_worker_time/1000 AS [總消耗CPU 時間(ms)],execution_count [執行次數], qs.total_worker_time/qs.execution_count/1000 AS [平均消耗CPU 時間(ms)], last_execution_time AS [最後一次執行時間],max_worker_time /1000 AS [最大執行時間(ms)], SUBSTRING(qt.text,qs.statement_start_offset/2+1, (CASE WHEN qs.statement_end_offset = -1 THEN DATALENGTH(qt.text) ELSE qs.statement_end_offset END -qs.statement_start_offset)/2 + 1) AS [使用CPU的語法], qt.text [完整語法], dbname=db_name(qt.dbid), object_name(qt.objectid,qt.dbid) ObjectName FROM sys.dm_exec_query_stats qs WITH(nolock) CROSS apply sys.dm_exec_sql_text(qs.sql_handle) AS qt WHERE execution_count>1 ORDER BY total_worker_time DESC