获取SQL维护作业的最新运行时间

时间:2016-11-04 08:34:18

标签: sql-server-2012

我正在尝试使用以下查询获取SQL中维护作业的状态。

USE msdb
GO
SELECT Distinct SJ.Name AS "Jobs/Sql ServerInstances",
CONVERT(date, getdate(),101) as "Date last monitored",
SJH.run_date AS "Date last run", 
CASE SJH.run_status 
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Successful'
WHEN 3 THEN 'Cancelled'
WHEN 4 THEN 'In Progress'
END AS LastRunStatus
FROM sysjobhistory SJH, sysjobs SJ
WHERE SJH.job_id = SJ.job_id and SJH.run_date = 
(SELECT MAX(SJH1.run_date) FROM sysjobhistory SJH1 WHERE SJH.job_id = SJH1.job_id)
and SJ.Name  like '%DB%'
ORDER BY SJH.run_date desc

以下是它返回的结果。

Jobs/Sql ServerInstances    Date last monitored Date last run   LastRunStatus
DB_BackuPlan.15min_trx      2016-11-04          20161104        Failed
DB_BackuPlan.15min_trx      2016-11-04          20161104        Successful
DB_BackuPlan.Differential   2016-11-04          20161104        Successful
DB_BackuPlan.Full           2016-11-04          20161029        Successful

但是,我想只返回事务日志备份的最新记录。我知道DISTINCT关键字将在行级而不是列级别上搜索(因此返回两个结果,一个用于状态失败,另一个用于同一作业的状态成功)。 有没有办法只返回上述工作的最新运行信息?

1 个答案:

答案 0 :(得分:1)

我已添加以下更改:

由于sysjobhistory使用两个不同的(int)字段保存run_daterun_timeSELECT Top 1 [instance_id] ... order by [run_date] desc可能无法返回所需的行。

要解决这个问题,我已经改变了:

order by dbo.agent_datetime(run_date,run_time) desc

使用datetime[run_date]

返回[run_time]
use msdb
go

with jobs_cte as
(
select 
    sj.[job_id]
    ,sj.[name]
    ,[date last monitored] = convert(datetime, getdate(), 101)
    ,[instance_id] = (select top 1 [instance_id] 
                      from [sysjobhistory] 
                      where [sysjobhistory].job_id = sj.job_id 
                      order by dbo.agent_datetime(run_date,run_time) desc)
from 
    sysjobs sj
where 
    sj.[name] like '%DB%'
)
select
    jobs_cte.job_id
    ,jobs_cte.[name]
    ,[date last monitored]
    , case [sjh].[run_status]
        when 0 then 'Failed'
        when 1 then 'Successful'
        when 3 then 'Cancelled'
        when 4 then 'In Progress'
    end as [lastrunstatus]
from
    jobs_cte
    left join sysjobhistory sjh
        on jobs_cte.instance_id = sjh.instance_id