As I am getting used to the new environment, I wanted to keep tabs on SQL Server Agent job and see how the database growth is impacting SQL Server Agent jobs in terms of duration (daily). I had stumbled upon a query to analyze it by hour and that would work in data warehouse situations where ETL is happening every hour. My objective was to analyze it by days, and have it dynamic (had to monkey around with PIVOT function and dynamic columns). Finally, bingo!
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 38 39 40 41 42 43 44 45 46 47 48 | DECLARE @columns VARCHAR(2000) , @query VARCHAR(8000) SELECT @columns = COALESCE ( @columns + ',[' + CONVERT(VARCHAR, run_date) + ']', + '[' + CONVERT(VARCHAR, run_date) + ']' ) from msdb.dbo.sysjobhistory group by run_date order by run_date SET @query = ' ;WITH JobHistory AS ( SELECT b.name as JobName , a.run_date as [RunDate] ,(a.run_duration / 10000 * 60 * 60 -- Hours + a.run_duration % 10000 / 100 * 60 -- Minutes + a.run_duration % 100 -- Seconds ) / 60.0 AS [DurationMinutes] FROM msdb.dbo.sysjobhistory a WITH(NOLOCK) INNER JOIN msdb.dbo.sysjobs b WITH(NOLOCK) ON a.[job_id] = b.[job_id] -- AND b.[name] = @JobName AND step_id = 0 AND run_status = 1 ) SELECT * FROM JobHistory PIVOT ( SUM(DurationMinutes) FOR [RunDate] in (' + @columns + ') ) as pvt order by JobName' exec(@query) |
The original idea about trending by hour was acquired from:
http://timlaqua.com/2009/12/trending-sql-server-agent-job-duration-by-hour/