sqlserver cpu占用高问题记录

--查询 CPU占用时间最长的的查询
SELECT TOP 10
[session_id],
[request_id],
[start_time] AS '开始时间',
[status] AS '状态',
[command] AS '命令',
dest.[text] AS 'sql语句',
DB_NAME([database_id]) AS '数据库名',
cpu_time,
[blocking_session_id] AS '正在阻塞其他会话的会话ID',
[wait_type] AS '等待资源类型',
[wait_time] AS '等待时间',
[wait_resource] AS '等待的资源',
[reads] AS '物理读次数',
[writes] AS '写次数',
[logical_reads] AS '逻辑读次数',
[row_count] AS '返回结果行数'
FROM sys.[dm_exec_requests] AS der
CROSS APPLY
sys.[dm_exec_sql_text](der.[sql_handle]) AS dest
WHERE [session_id]>50-- AND DB_NAME(der.[database_id])='你的数据库名注意前面的注释'
ORDER BY [cpu_time] DESC

-- cpu占用最高的 查询
SELECT TOP 10
total_worker_time/execution_count AS avg_cpu_cost, plan_handle,
execution_count,
(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)) AS query_text,dbname=db_name(s2.dbid)
FROM sys.dm_exec_query_stats as s1 CROSS APPLY sys.dm_exec_sql_text(s1.sql_handle) AS s2
ORDER BY [avg_cpu_cost] DESC


-- 影响 查询 的 索引丢失查询    --因为没有索引并且使用次数多的时候也会使资源占用很大.
SELECT top 10
DatabaseName = DB_NAME(database_id)
,[Number Indexes Missing] = count(*)
FROM sys.dm_db_missing_index_details
GROUP BY DB_NAME(database_id)
ORDER BY 2 DESC;
SELECT TOP 10
[Total Cost] = ROUND(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0)
, avg_user_impact
, TableName = statement
, [EqualityUsage] = equality_columns
, [InequalityUsage] = inequality_columns
, [Include Cloumns] = included_columns
FROM sys.dm_db_missing_index_groups g
INNER JOIN sys.dm_db_missing_index_group_stats s
ON s.group_handle = g.index_group_handle
INNER JOIN sys.dm_db_missing_index_details d
ON d.index_handle = g.index_handle
ORDER BY [Total Cost] DESC;

 

 查询某个表被哪个服务器执行的什么语句锁了

SELECT
r.session_id,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
r.blocking_session_id,
r.start_time,
r.lock_timeout,

s.login_name,
s.host_name,
st.text AS query_text
FROM sys.dm_exec_requests r
INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) st
INNER JOIN sys.dm_tran_locks l ON r.session_id = l.request_session_id
WHERE
l.resource_type = 'OBJECT'
AND l.resource_associated_entity_id = OBJECT_ID('表名')
ORDER BY r.session_id;

综上查询 后 再根据具体的问题去分析 处理

posted @ 2022-07-18 15:49  望着天的蜗牛  阅读(183)  评论(0编辑  收藏  举报