forked from DavidWiseman/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet_CPU_Usage_Per_Database.sql
37 lines (36 loc) · 1.32 KB
/
Get_CPU_Usage_Per_Database.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
<documentation>
<summary>Get CPU Usage Per Database</summary>
<returns>1 data set with 2 columns: database name and CPUTimeAsPercentage.</returns>
<issues>No</issues>
<author>Eli Leiba</author>
<created>2019-11-05</created>
<modified>2019-11-05</modified>
<version>1.0</version>
<originalLink>https://www.mssqltips.com/sqlservertip/6195/sql-server-function-to-measure-cpu-usage-per-database/</originalLink>
<sourceLink>https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_CPU_Usage_Per_Database.sql</sourceLink>
</documentation>
*/
SELECT
T.[Database]
, T.CPUTimeAsPercentage
FROM
(SELECT
[Database],
CONVERT (DECIMAL (6, 3), [CPUTimeInMiliSeconds] * 1.0 /
SUM ([CPUTimeInMiliSeconds]) OVER () * 100.0) AS [CPUTimeAsPercentage]
FROM
(SELECT
dm_execplanattr.DatabaseID,
DB_Name(dm_execplanattr.DatabaseID) AS [Database],
SUM (dm_execquerystats.total_worker_time) AS CPUTimeInMiliSeconds
FROM sys.dm_exec_query_stats dm_execquerystats
CROSS APPLY
(SELECT
CONVERT (INT, value) AS [DatabaseID]
FROM sys.dm_exec_plan_attributes(dm_execquerystats.plan_handle)
WHERE attribute = N'dbid'
) dm_execplanattr
GROUP BY dm_execplanattr.DatabaseID
) AS CPUPerDb
) AS T;