1

有没有办法使用 DMV 获取 SQL Server 2005 中每个会话或每个打开连接的 CPU 时间?我尝试了 sys.dm_exec_query_stats、sys.dm_exec_connections、sys.dm_exec_sessions 的各种组合。我是否缺少其他一些明显的方式来获取相同的信息?我的环境是一个 SQL Server 2005,有大约 100 个数据库,其中一个数据库占用大约 40% 的 CPU(使用下面的查询找到),我试图弄清楚是什么(连接数、什么查询等)占用了 40 个%。

该脚本为每个数据库提供 CPU 时间。我只需要将其分解为会话或至少在连接级别。

WITH DB_CPU_Stats
AS
(SELECT DatabaseID, DB_Name(DatabaseID) AS [DatabaseName], 
  SUM(total_worker_time) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
       DatabaseName, [CPU_Time_Ms], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) 
       OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
FROM DB_CPU_Stats
WHERE DatabaseID > 4 -- system databases
AND DatabaseID <> 32767 -- ResourceDB
ORDER BY row_num

感谢您是否可以提供工作样本。

更新:

修改了上面的查询 - 这足够好吗?只想找人验证...

WITH DB_CPU_Stats
AS
(SELECT DatabaseID, DB_Name(DatabaseID) AS [DatabaseName], sql_handle,
  SUM(total_worker_time) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
 GROUP BY DatabaseID, sql_handle
)


SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
       DatabaseName, [CPU_Time_Ms],  text, count(1) as Connections,
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) 
       OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
FROM DB_CPU_Stats
cross apply sys.dm_exec_sql_text(sql_handle) C
join sys.dm_exec_connections CON on CON.most_recent_sql_handle = sql_handle
WHERE DatabaseID > 4 -- system databases
AND DatabaseID <> 32767 -- ResourceDB
GROUP BY CPU_Time_Ms, DatabaseName, text
ORDER BY row_num

dm_exec_connections 的 most_recent_handle 是否应该映射到 dm_exec_query_text 的 sql_handle?

4

0 回答 0