隐藏

mssql查询死锁,并杀死死锁进程

发布:2022/4/21 11:29:39作者:管理员 来源:本站 浏览次数:1033


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


SELECT TOP 100
 [session_id],
 [request_id],
 [start_time] AS '开始时间',
 [status] AS '状态',
 [command] AS '命令',
 dest.[text] AS 'sql语句',
 DB_NAME([database_id]) AS '数据库名',
 [blocking_session_id] AS '正在阻塞其他会话的会话ID',
 der.[wait_type] AS '等待资源类型',
 [wait_time] AS '等待时间',
 [wait_resource] AS '等待的资源',
 [dows].[waiting_tasks_count] AS '当前正在进行等待的任务数',
 [reads] AS '物理读次数',
 [writes] AS '写次数',
 [logical_reads] AS '逻辑读次数',
 [row_count] AS '返回结果行数'
 FROM sys.[dm_exec_requests] AS der
 INNER JOIN [sys].[dm_os_wait_stats] AS dows
 ON der.[wait_type]=[dows].[wait_type]
 CROSS APPLY
 sys.[dm_exec_sql_text](der.[sql_handle]) AS dest
 WHERE [session_id]>50
 ORDER BY [cpu_time] DESC



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




-----------------------------------------------------------------------------------
declare @spid int
declare @tableName varchar (50)
declare @str varchar (50)
 
--定义一个游标

declare user_cur cursor for
SELECT request_session_id spid,OBJECT_NAME(resource_associated_entity_id)tableName FROM sys.dm_tran_locks WHERE resource_type='OBJECT '

--打开游标
open user_cur
while @@fetch_status=0
begin
--读取游标
   fetch next from user_cur into @spid,@tableName
   print @spid
   set @str= 'KILL '+convert(varchar(20),@spid)
   exec(@str)
   --print @Login
end
close user_cur
--摧毁游标
deallocate user_cur
-------------------------------------------------------------------------------------------------