SQLServer Jobhistory - 上次成功运行时&最后一次失败的运行时

时间:2016-09-27 12:42:26

标签: sql sql-server sql-server-2016 sql-job

我想了解一下我的sql作业,其中包含

USE msdb GO SELECT DISTINCT SJ.Name AS JobName, SJH.run_date AS LastRunDate, SJH.job_id, (SELECT MAX(DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME)) FROM sysjobs RIGHT JOIN sysjobhistory ON SJ.job_id = SJH.job_id WHERE SJH.run_status = 1) AS LastSuccessfulRun, 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(SJH.run_date) FROM sysjobhistory SJH WHERE SJ.job_id = SJH.job_id)

这是我在上次成功运行日期中找到的内容。 像魅力一样,但我在这里,没有添加最后一次运行日期。

onBindViewHolder

这是我到目前为止得到的结果,但是它给了我两行的结果,一行是最后一次运行日期,另一行是最后一次成功运行(这是不正确的,因为它选择了最高的日期 - 不同的值)。我请求帮助以使连接正确并将结果放在一行。

holder.yourItem.setTag(position);

2 个答案:

答案 0 :(得分:0)

我想你想要row_number()

SELECT x.*
FROM (SELECT SJ.NAME AS [Job Name], RUN_STATUS AS [Run Status],
             DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) AS LastRunDateTime,
             ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) DESC) as seqnum
      FROM dbo.SYSJOBS SJ LEFT OUTER JOIN
           dbo.SYSJOBHISTORY JH
           ON SJ.job_id = JH.job_id
      WHERE JH.step_id = 0 AND jh.run_status = 1
      GROUP BY SJ.name, JH.run_status 
     ) x
WHERE seqnum = 1
ORDER BY LastRunDateTime DESC;

此外,学会使用正确的,明确的JOIN语法。 FROM条款中的逗号是陈旧的。

答案 1 :(得分:0)

解决方案是:

SELECT sj.name,
        MAX(dbo.agent_datetime(sjh.run_date, sjh.run_time)) AS last_Succesful_run,
        x.last_Unsuccesful_run
FROM    sysjobhistory sjh
        INNER JOIN sysjobs sj ON sjh.job_id = sj.job_id
LEFT OUTER JOIN
     (SELECT sysjobs.name,
                MAX(dbo.agent_datetime(sysjobhistory.run_date, sysjobhistory.run_time)) AS last_Unsuccesful_run
        FROM    sysjobhistory
        INNER JOIN sysjobs ON sysjobhistory.job_id = sysjobs.job_id
        WHERE sysjobhistory.run_status = 0
        GROUP BY sysjobs.name) x
        ON x.name = sj.name
WHERE   run_status = 1 
GROUP BY sj.job_id, sj.name, last_Unsuccesful_run

放弃状态案例,这样就足够清楚了。案件不是强制性的。