标签:
SQL Server将Job的信息存放在msdb中,Schema是dbo,表名以“sysjob”开头。
1, 使用 msdb.dbo.sysjobs 和 msdb.dbo.sysjobsteps 查看Job和job的step,Step_ID 是从1 开始的。
select j.job_id,j.name,j.enabled,j.description, j.start_step_id,j.date_created,j.date_modified from msdb.dbo.sysjobs j with(nolock) where name =N‘xxx‘
2, 使用 msdb.dbo.sysjobhistory 查看 job 所有 Step的history,Step_id=0是对job整体的执行情况的一个历史记录。
run_time 和 run_duration 是int类型,格式是hhmmss。
select jh.instance_id,jh.job_id,jh.step_id,jh.step_name,jh.sql_message_id,jh.sql_severity, jh.message,jh.run_status, jh.run_date,jh.run_time,jh.run_duration from msdb.dbo.sysjobhistory jh with(nolock) where job_id=N‘07A53839-E012-4C80-9227-15594165B013‘ order by instance_id desc --Status of the job execution: -- 0 = Failed -- 1 = Succeeded -- 2 = Retry -- 3 = Canceled
3,Job History的查询
Script1
--查看每个job最近10次执行情况 ;with cte_job as ( select j.job_id,j.name,j.enabled, jh.run_status,jh.message,jh.run_date,jh.run_time,jh.run_duration,jh.sql_message_id,jh.sql_severity, ROW_NUMBER() over(PARTITION by j.job_id ORDER by jh.run_date desc,jh.run_time) as rid from msdb.dbo.sysjobs j with(nolock) inner join msdb.dbo.sysjobhistory jh with(nolock) on j.job_id=jh.job_id where jh.step_id=0 ) select c.name as JobName,c.enabled,c.run_status,c.message, c.run_date,c.run_time,c.run_duration,c.sql_message_id,c.sql_severity from cte_job as c where c.rid<=10 --and c.name=N‘Filter_Job_Name‘ order by c.job_id,c.run_date desc,c.run_time desc
Script2
--查看job 最后一次执行的情况 DECLARE @Job_ID uniqueidentifier; select @Job_ID=j.job_id from msdb.dbo.sysjobs j with(nolock) where j.name=N‘JobName‘ ;with cte as ( select jh.job_id,jh.run_date,jh.run_time,jh.run_status, ROW_NUMBER() over(PARTITION by jh.job_id order by jh.run_date desc,jh.run_time desc) as rid from msdb.dbo.sysjobhistory jh with(NOLOCK) where jh.step_id=0 and jh.job_id=@Job_ID ) , cte_Last AS ( select job_id,Last_Run_Date=run_date,Last_Run_Time=run_time from cte where rid=2 ) select j.name as JobName, jh.step_id,jh.step_name,jh.run_status,jh.message, jh.run_date,jh.run_time,jh.run_duration from msdb.dbo.sysjobs j with(nolock) inner join msdb.dbo.sysjobhistory jh with(nolock) on jh.job_id=j.job_id inner join cte_last as cl on j.job_id=cl.job_id where jh.run_date>cl.Last_Run_Date and jh.run_time>cl.Last_Run_Time order by jh.step_id asc
参考文档:
SQL Server Agent Tables (Transact-SQL)
标签:
原文地址:http://www.cnblogs.com/ljhdo/p/5498433.html