Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Register Now and get your question answered!
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 Script Library
 Querying msdb for job history
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Norsk Yak Master

3271 Posts

Posted - 02/21/2013 :  09:14:53  Show Profile  Reply with Quote
I recently had the need to create an SSRS report showing the status of some jobs from the 10 last days, so I wrote this script that I thought could come in handy to others as well. The contents should be pretty self explanatory except maybe for the RowNum column which is there to separate each iteration of the job:

WITH cte_jobhistory AS (
		--> Creating a cte only to make the columns run_date and run_time into a "datetime-friendly" format  
		--  so it can be used for filtering
			RunDateString = 
				SUBSTRING(CAST(run_date as VARCHAR(20)), 1, 4) + '-' +  
				SUBSTRING(CAST(run_date as VARCHAR(20)), 5, 2) + '-' + 
				SUBSTRING(CAST(run_date as VARCHAR(20)), 7, 2),
			RunTimeString = 
				SUBSTRING(RIGHT('000000' + CAST(run_time as VARCHAR(20)), 6), 1, 2) + ':' + 
				SUBSTRING(RIGHT('000000' + CAST(run_time as VARCHAR(20)), 6), 3, 2) + ':' + 
				SUBSTRING(RIGHT('000000' + CAST(run_time as VARCHAR(20)), 6), 5, 2),
		FROM msdb.dbo.sysjobhistory
	RowNum = ROW_NUMBER() OVER (PARTITION BY, b.step_id ORDER BY instance_id DESC),
	RunStatus = CASE b.run_status 
		WHEN 0 THEN 'Failed'
		WHEN 1 THEN 'Succeded' 
		WHEN 2 THEN 'Retry' 
		WHEN 3 THEN 'Cancelled' 
		WHEN 4 THEN 'In Progress' 
FROM msdb.dbo.sysjobs a
	INNER JOIN cte_jobhistory b
		ON a.job_id = b.job_id
WHERE CONVERT(datetime, b.RunDateString) > GETDATE()-10
ORDER BY ASC, b.instance_id DESC

- Lumbago
My blog->

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 02/21/2013 :  22:58:22  Show Profile  Reply with Quote
Thanks for this. SQL 2012 has Job Execution history report available as a standard report within SSMS.

SQL Server MVP

Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000