Get SQL Server CPU between dates

nd0911 86 Reputation points
2023-03-01T12:05:28.88+00:00

Hello,

I have this query that returns the CPU per databases

SELECT 
	DB_Name(p.DatabaseID) AS DbName
	,SUM(q.total_worker_time) AS CpuTimeInMiliSeconds
FROM 
	sys.dm_exec_query_stats q 
	CROSS APPLY 
	(
		SELECT 
			CONVERT (INT, value) AS [DatabaseID]
		FROM 
			sys.dm_exec_plan_attributes(q.plan_handle)
		WHERE 
			attribute = N'dbid'
	) as p
GROUP BY
	p.DatabaseID
order by
	CPUTimeInMiliSeconds desc

Is there a way to add a WHERE filter between two dates, so i will get only the sum of "CpuTimeInMiliSeconds" between these dates ?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zahid Butt 956 Reputation points
    2023-03-01T13:07:28.1766667+00:00

    Hi,

    Please find below updated query (you can have last*executiontime or creation_*time):

    SELECT 
    	DB_Name(p.DatabaseID) AS DbName
    	,SUM(q.total_worker_time) AS CpuTimeInMiliSeconds
    FROM 
    	sys.dm_exec_query_stats q 
    	CROSS APPLY 
    	(
    		SELECT 
    			CONVERT (INT, value) AS [DatabaseID]
    		FROM 
    			sys.dm_exec_plan_attributes(q.plan_handle)
    		WHERE 
    			attribute = N'dbid'
    	) as p
    where convert(date,q.last_execution_time) between '02/28/2023' and '03/01/2023'
    --where convert(date,q.creation_time) between '02/28/2023' and '03/01/2023'
    GROUP BY
    	p.DatabaseID
    order by
    	CPUTimeInMiliSeconds desc
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.