Sql Server 表被锁?查看 高CPU sql ?(SQL Server table locked? View high CPU SQL?)

Sql Server 表被锁?查看 高CPU sql ?

-- 1. 查看 被锁的表,和锁表进程id

select request_session_id 锁表进程, OBJECT_NAME(resource_associated_entity_id) 被锁表名  
from sys.dm_tran_locks where resource_type = 'OBJECT'



-- 2. 查看 cpu 占用高 的sql 语句
 SELECT TOP 100
   total_worker_time/execution_count AS avg_cpu_cost, plan_handle,
   execution_count,
   (SELECT SUBSTRING(text, statement_start_offset/2 + 1,
      (CASE WHEN statement_end_offset = -1
         THEN LEN(CONVERT(nvarchar(max), text)) * 2
         ELSE statement_end_offset
      END - statement_start_offset)/2)
   FROM sys.dm_exec_sql_text(sql_handle)) AS query_text
FROM sys.dm_exec_query_stats
where last_execution_time > '2022-01-11 02:00:39.397'
ORDER BY [avg_cpu_cost] DESC

-- 3. 解锁(干掉解锁进程)
declare @spid  int
Set @spid  = 66 -- 锁表进程
declare @sql varchar(1000)
set @sql = 'kill ' + cast(@spid as varchar)
exec(@sql)
————————

Sql Server 表被锁?查看 高CPU sql ?

-- 1. 查看 被锁的表,和锁表进程id

select request_session_id 锁表进程, OBJECT_NAME(resource_associated_entity_id) 被锁表名  
from sys.dm_tran_locks where resource_type = 'OBJECT'



-- 2. 查看 cpu 占用高 的sql 语句
 SELECT TOP 100
   total_worker_time/execution_count AS avg_cpu_cost, plan_handle,
   execution_count,
   (SELECT SUBSTRING(text, statement_start_offset/2 + 1,
      (CASE WHEN statement_end_offset = -1
         THEN LEN(CONVERT(nvarchar(max), text)) * 2
         ELSE statement_end_offset
      END - statement_start_offset)/2)
   FROM sys.dm_exec_sql_text(sql_handle)) AS query_text
FROM sys.dm_exec_query_stats
where last_execution_time > '2022-01-11 02:00:39.397'
ORDER BY [avg_cpu_cost] DESC

-- 3. 解锁(干掉解锁进程)
declare @spid  int
Set @spid  = 66 -- 锁表进程
declare @sql varchar(1000)
set @sql = 'kill ' + cast(@spid as varchar)
exec(@sql)