触发器造成死锁、作业多且频繁、中间表的大量使用、游标的大量使用、索引的设计不合理、事务操作频繁、SQL语句设计不合理,都会造成查询效率低下、影响服务器性能的发挥。我们可以使用sql server自带的性能分析追踪工具sql profiler分析数据库设计所产生问题的来源,进行有针对性的处理;下面小编收集了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])='gposdb'
SELECT COUNT(*) FROM [sys].[dm_exec_sessions] WHERE [session_id]>50
2、查CPU使用率前10 的SQL语句:
SELECT
TOP
10
st.text
AS
SQL_Full
--父级完整语句
,
SUBSTRING
(st.text, (qs.statement_start_offset/2) + 1,
((
CASE
statement_end_offset
WHEN
-1
THEN
DATALENGTH(st.text)
ELSE
qs.statement_end_offset
END
- qs.statement_start_offset)/2) + 1)
as
SQL_Part
--统计对应的部分语句
,
CAST
( ((qs.total_elapsed_time / 1000000.0)/qs.execution_count)
AS
DECIMAL
(28,2) )
AS
[平均消耗秒数]
,
CAST
(qs.last_elapsed_time / 1000000.0
AS
DECIMAL
(28, 2))
AS
[最后完成消耗秒数]
, qs.last_execution_time
AS
[最后执行时间]
,
CAST
(qs.min_elapsed_time / 1000000.0
AS
DECIMAL
(28, 2))
AS
[最小消耗秒数]
,
CAST
(qs.max_elapsed_time / 1000000.0
AS
DECIMAL
(28, 2))
AS
[最大消耗秒数]
,
CAST
(qs.total_elapsed_time / 1000000.0
AS
DECIMAL
(28, 2))
AS
[总消耗秒数]
, (qs.execution_count)
AS
[总执行次数]
, creation_time
AS
[编译计划的时间]
,
CAST
(qs.last_worker_time / 1000000.0
AS
DECIMAL
(28, 2))
AS
[最后完成占用CPU秒数]
, qp.query_plan
from
sys.dm_exec_query_stats qs
CROSS
APPLY sys.dm_exec_sql_text(qs.sql_handle)
AS
st
CROSS
APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE
qs.last_execution_time>DATEADD(n,-30,GETDATE())
ORDER
BY
qs.last_worker_time
DESC
3、查阻塞:
SELECT R.session_id AS BlockedSessionID ,
S.session_id AS BlockingSessionID ,
Q1.text AS BlockedSession_TSQL ,
Q2.text AS BlockingSession_TSQL ,
C1.most_recent_sql_handle AS BlockedSession_SQLHandle ,
C2.most_recent_sql_handle AS BlockingSession_SQLHandle ,
S.original_login_name AS BlockingSession_LoginName ,
S.program_name AS BlockingSession_ApplicationName ,
S.host_name AS BlockingSession_HostName
FROM sys.dm_exec_requests AS R
INNER JOIN sys.dm_exec_sessions AS S ON R.blocking_session_id = S.session_id
INNER JOIN sys.dm_exec_connections AS C1 ON R.session_id = C1.most_recent_session_id
INNER JOIN sys.dm_exec_connections AS C2 ON S.session_id = C2.most_recent_session_id
CROSS APPLY sys.dm_exec_sql_text(C1.most_recent_sql_handle) AS Q1
CROSS APPLY sys.dm_exec_sql_text(C2.most_recent_sql_handle) AS Q2