利用SQL查看JOB执行的状况

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值