日期:2014-05-17 浏览次数:20858 次
SELECT sj.name as job, left(sjh_d.step_name, 20) as [step name],
--What is it in English
CASE sjh.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
ELSE 'Unknown'
END as status,
--Convert Integer date to regular datetime
SUBSTRING(CAST(sjh.run_date AS CHAR(8)),5,2) + '/' +
RIGHT(CAST(sjh.run_date AS CHAR(8)),2) + '/' +
LEFT(CAST(sjh.run_date AS CHAR(8)),4) as [date]
--Change run time into something you can recognize (hh:mm:ss)
, LEFT(RIGHT('000000' + CAST(sjh.run_time AS VARCHAR(10)),6),2) + ':' +
SUBSTRING(RIGHT('000000' + CAST(sjh.run_time AS VARCHAR(10)),6),3,2) + ':' +
RIGHT(RIGHT('000000' + CAST(sjh.run_time AS VARCHAR(10)),6),2) as [time]
--error message
,sjh_d.message as error
FROM msdb.dbo.sysjobs sj --job id and name
--Job history
INNER JOIN msdb.dbo.sysjobhistory sjh
ON sj.job_id = sjh.job_id
--fail details
LEFT JOIN msdb.dbo.sysjobhistory sjh_d
ON sjh.job_id = sjh_d.job_id AND sjh_d.step_id > 0
--Only enabled jobs
WHERE sj.enabled = 1
--Only job outcome not each step outcome
AND sjh.step_id = 0
--Only failed or cancelled jobs
AND (sjh.run_status = 0 OR sjh.run_status = 3)
--Latest date first
ORDER BY sjh.run_date DESC