码迷,mamicode.com
首页 > 数据库 > 详细

SqlServer中检查CPU资源运行状态

时间:2019-12-14 14:15:01      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:execution   status   RoCE   task   where   and   数据库名   app   情况   

SQL Server中查询CPU占用高的SQL语句

SQL Server中查询CPU占用高的情况,会用到sys.sysprocesses ,dm_exec_sessions ,dm_exec_requests

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

2、选取前10个最耗CPU时间的会话 

SELECT TOP 10
[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‘,
[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

3、查询前10个最耗CPU时间的SQL语句

SELECT TOP 10 
dest.[text] AS ‘sql语句‘
FROM sys.[dm_exec_requests] AS der 
CROSS APPLY 
sys.[dm_exec_sql_text](der.[sql_handle]) AS dest 
WHERE [session_id]>50  
ORDER BY [cpu_time] DESC

4、查询会话中有多少个worker在等待 

SELECT TOP 10
[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

5、查询CPU占用高的语句

SELECT TOP 10
   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

  

SqlServer中检查CPU资源运行状态

标签:execution   status   RoCE   task   where   and   数据库名   app   情况   

原文地址:https://www.cnblogs.com/approx/p/12038743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!