SQL查询获取SQL Server中所有作业的状态

时间:2015-11-04 09:31:37

标签: sql-server

我需要一个SQL查询,它应该为我提供SQL服务器中所有作业的最新状态。

在Query下面我试图获取状态,但它不会给出SQL Server中所有作业的状态。

SELECT  DISTINCT name AS [Job Name],
    CASE WHEN enabled=1 THEN 'Enabled'  
        ELSE 'Disabled'  
    END [Job Status],
    CASE    WHEN SJH.run_status=0 THEN 'Failed'
            WHEN SJH.run_status=1 THEN 'Succeeded'
            WHEN SJH.run_status=2 THEN 'Retry'
            WHEN SJH.run_status=3 THEN 'Cancelled'
    ELSE 'Unknown'  
    END [Job Outcome],
    sjh.run_date,
    sjh.run_time
FROM    SYSJobs sj
LEFT    JOIN    SYSJobHistory sjh
ON      sj.job_id = sjh.job_id
WHERE   (
    sjh.run_date IN (
                    SELECT  MAX(sjh1.run_date)
                    FROM    SYSJobHistory sjh1
                    WHERE   sjh.job_id = sjh1.job_id
                    )
    OR sjh.run_date IS NULL
    )
AND     (
    sjh.run_time IN (
                    SELECT  MAX(sjh1.run_time)
                    FROM    SYSJobHistory sjh1
                    WHERE   sjh.job_id = sjh1.job_id
                    )
    OR  sjh.run_time IS NULL
    )
 ORDER  BY [Job Name]

2 个答案:

答案 0 :(得分:0)

使用此

select distinct j.Name as "Job Name", 
case jh.run_status  
when 0 then 'Failed'  
when 1 then 'Successful'  
when 2 then 'Retry' 
when 3 then 'Cancelled'  
when 4 then 'In Progress'  
end as Job_Execution_Status 
from sysJobHistory jh, sysJobs j 
where j.job_id = jh.job_id

答案 1 :(得分:0)

尝试使用Row_Number()

;With Cte
as
(
    SELECT  name AS [Job Name],
        CASE WHEN enabled=1 THEN 'Enabled'  
            ELSE 'Disabled'  
        END [Job Status],
      CASE    WHEN SJH.run_status=0 THEN 'Failed'
        WHEN SJH.run_status=1 THEN 'Succeeded'
        WHEN SJH.run_status=2 THEN 'Retry'
        WHEN SJH.run_status=3 THEN 'Cancelled'
        ELSE 'Unknown'  
        END [Job Outcome],
        sjh.run_date,
        sjh.run_time,Row_Number() Over(Partition by name Order By sjh.run_date desc,sjh.run_time desc) as rn
    FROM    SYSJobs sj
    LEFT    JOIN    SYSJobHistory sjh
    ON      sj.job_id = sjh.job_id
)

select * from cte where rn=1

如果您不了解情景,请查看Row_Number()