mssql sqlserver 数据库服务器CPU占用一直大于百分之80的解决方法分享


摘要:
下文讲述一次sqlserver CPU占用高的处理方法,记录如下,
实验环境:sqlserver 2008 R2



排查方法1:
获取当前数据库用户连接数,是否在正常及合理的范围
USE master
GO

SELECT * FROM sys.[sysprocesses] WHERE [spid]>50 –AND DB_NAME([dbid])=’数据库名称’
SELECT COUNT(*) FROM [sys].[dm_exec_sessions] WHERE [session_id]>50
如果获取用户连接数,不在预估的范围中,请排查用户连接数增多的原因,及数据库硬件增加或数据库负载均衡(分流措施)等

1.mssql_sqlserver_用户连接数查询

1.mssql_sqlserver_用户连接数查询



排查方法2:
获取CPU运行耗时最长的20个sql脚本
USE master
GO
SELECT TOP 20
[session_id],
[request_id],
[start_time] AS ‘脚本运行开始时间’,
[status] AS ‘脚本当前状态’,
[command] AS ‘脚本运行方式’,
b.[text] AS ‘脚本内容’,
DB_NAME([database_id]) AS ‘数据库’,
[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 a
CROSS APPLY
sys.[dm_exec_sql_text](a.[sql_handle]) AS b
WHERE [session_id]>50 —AND DB_NAME(a.[database_id])=’数据库名称’
ORDER BY [cpu_time] DESC

—查看CPU占用高的sql脚本
SELECT TOP 20
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
ORDER BY [avg_cpu_cost] DESC


将前20条sql脚本,进行单独的优化,看是否缺少索引,或者阻塞,需具体情况具体对待
2.mssql_sqlserver_最耗CPU时间的前20条脚本

2.mssql_sqlserver_最耗CPU时间的前20条脚本



排查方法3:
查看索引缺失情况:
SELECT
[数据库名称] = DB_NAME(database_id)
,[索引缺失合计] = count(*)
FROM sys.dm_db_missing_index_details
GROUP BY DB_NAME(database_id)
ORDER BY 1 DESC;

—-缺少索引的表,及缺少索引的字段
SELECT TOP 20
[CPU总消耗] = ROUND(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0)
,avg_user_impact
,[表名] = statement
,[索引涉及列]= equality_columns
,[其它比较列]=inequality_columns
,[包含列]=included_columns
FROM sys.dm_db_missing_index_groups a
INNER JOIN sys.dm_db_missing_index_group_stats b
ON b.group_handle = a.index_group_handle
INNER JOIN sys.dm_db_missing_index_details c
ON c.index_handle = a.index_handle
ORDER BY [CPU总消耗] DESC;


对缺失索引的表上,建立索引后,CPU得到明显的下降
—-重新建立索引后,CPU占用得到明显的下降