查询CPU占⽤⾼的SQL语句的解决⽅案
触发器造成死锁、作业多且频繁、中间表的⼤量使⽤、游标的⼤量使⽤、索引的设计不合理、事务操作频繁、SQL语句设计不合理,都会造成查询效率低下、影响服务器性能的发挥。我们可以使⽤sql server⾃带的性能分析追踪⼯具sql profiler分析数据库设计所产⽣问题的来源,进⾏有针对性的处理;下⾯⼩编收集了SQL Server中如何查询CPU占⽤⾼的SQL语句,希望⼤⼤家能有所帮助。
注意:SQL Server中查询CPU占⽤⾼的情况,经常会⽤到sys.sysprocesses ,dm_exec_sessions ,dm_exec_requests
1、查看当前的数据库⽤户连接数
USE master
GO
sql触发器的使用SELECT * FROM sys.[sysprocesses] WHERE [spid]>50 --AND DB_NAME([dbid])='gposdb'
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])='gposdb'
ORDER BY [cpu_time] DESC
3、查询前10个最耗CPU时间的SQL语句
--在SSMS⾥选择以⽂本格式显⽰结果
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、查询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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。