CSDN博客

img tdl982324

利用SQL查看JOB执行的状况

发表于2004/9/29 16:11:00  3372人阅读

分类: SQL Server

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 DES

-------------------------------------------
简化版
-------------------------------------------
SELECT  a.name as job, left(b.step_name, 20) as [step name],
CASE b.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' WHEN 2 THEN 'Retry' WHEN 3 THEN 'Canceled' ELSE 'Running'  END as status,
SUBSTRING(CAST(b.run_date AS CHAR(8)),5,2) + '/' + RIGHT(CAST(b.run_date AS CHAR(8)),2) + '/' + LEFT(CAST(b.run_date AS CHAR(8)),4) as [date],
LEFT(RIGHT('000000' + CAST(b.run_time AS VARCHAR(10)),6),2) + ':' +  SUBSTRING(RIGHT('000000' + CAST(b.run_time AS VARCHAR(10)),6),3,2) + ':' +  RIGHT(RIGHT('000000' +  CAST(b.run_time AS VARCHAR(10)),6),2) as [time],
b.message as Err_message
From msdb..sysjobs a
INNER JOIN msdb..sysjobhistory b ON a.job_id = b.job_id
inner join (select job_id,max(instance_id)  as maxinstance from msdb..sysjobhistory  group by job_id) x
on a.job_id = x.job_id and b.instance_id = x.maxinstance
where a.enabled =1 and b.run_status <>1 and b.run_status <> 4
ORDER BY job, convert(char, b.run_date,111)+convert(char,b.run_time,111)  desc

阅读全文
0 0

相关文章推荐

img
取 消
img