Sql server SQL Server和sysjobhistory运行状态查询

Sql server SQL Server和sysjobhistory运行状态查询,sql-server,tsql,sql-server-2016,Sql Server,Tsql,Sql Server 2016,我在编写查询以执行我想要的操作时遇到问题。在SQL Server中,有一个名为msdb.dbo.sysjobhistory的系统表。它包含在服务器上运行和执行操作的SQL代理作业的历史记录。表的每一行对应于作业中的一个步骤。表中有一列名为run_status,它获取一个整数值,以指示作业完成并写入表中时的结果 我通过一些报告和简单的查询来跟踪此表中的信息。上周我发现了一个有趣的案例,我在报告中没有说明。在表中,即使每一行都是作业中的一个步骤,作业也有一个步骤0条目,作为总体结果。通常我只查看步骤

我在编写查询以执行我想要的操作时遇到问题。在SQL Server中,有一个名为msdb.dbo.sysjobhistory的系统表。它包含在服务器上运行和执行操作的SQL代理作业的历史记录。表的每一行对应于作业中的一个步骤。表中有一列名为run_status,它获取一个整数值,以指示作业完成并写入表中时的结果

我通过一些报告和简单的查询来跟踪此表中的信息。上周我发现了一个有趣的案例,我在报告中没有说明。在表中,即使每一行都是作业中的一个步骤,作业也有一个步骤0条目,作为总体结果。通常我只查看步骤0行,获取该行中作业的run_状态,并将其用作结果。但是,作业中的步骤可能具有“失败”状态,但步骤0中的总体作业结果具有“成功”状态。我提出了以下查询以查找这些情况:

SELECT job_id, step_id, step_name, run_date, run_time, run_status, W.parent_status
FROM msdb.dbo.sysjobhistory [H]
CROSS APPLY 
( SELECT TOP 1 run_status AS parent_status
  FROM msdb.dbo.sysjobhistory
  WHERE job_id = H.job_id
  AND run_date <= H.run_date
  AND step_id = 0
  AND (CASE WHEN run_date = H.run_date THEN run_Time ELSE H.run_time END) <= H.run_time
  ORDER BY run_date DESC, run_time DESC
) AS [W]
ORDER BY run_date, run_time, step_id
在这种情况下,run_状态为0表示失败,run_状态为1表示成功。 现在我有了这个表格,我想用它来找出一份工作到底发生了什么。我需要做一个CASE语句或类似的东西,在必要时覆盖步骤0的run_状态。因此,如果出现上述情况,那么我想将run_status的值改为2。现在,当我查询作业结果步骤时,我会得到类似于上述作业的结果:

job_id | step_id | step_name | run_date | run_time | run_status 
---------------------------------------------------------------
A12345 |    0    | (outcome) | 20170112 | 40000    |     2
我知道我想做什么,只是不知道如何编写SQL来完成。我需要以某种方式将父状态与所有运行状态结果进行比较,当父状态=1且运行状态=0时,则更改步骤0的运行状态。谢谢你的帮助

select
    (case when sh.run_status = 1 and tt.job_id is not null then 2 else sh.run_status end) as run_status
    , *
from dbo.sysjobhistory sh
    outer apply (
        select
            top (1)
            tsh.job_id
        from dbo.sysjobhistory tsh
        where sh.job_id = tsh.job_id
            and sh.step_id <> tsh.step_id
            and tsh.run_status = 0
    ) tt
select
    (case when sh.run_status = 1 and tt.job_id is not null then 2 else sh.run_status end) as run_status
    , *
from dbo.sysjobhistory sh
    outer apply (
        select
            top (1)
            tsh.job_id
        from dbo.sysjobhistory tsh
        where sh.job_id = tsh.job_id
            and sh.step_id <> tsh.step_id
            and tsh.run_status = 0
    ) tt