2015-11-04 81 views
0

我需要一個SQL查詢,它應該爲我提供SQL Server中所有作業的最新狀態。SQL查詢以獲取SQL Server中所有作業的狀態

查詢下面我試圖獲得狀態,但它不會給出SQL服務器中所有作業的狀態。

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] 

回答

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 

如果您din't瞭解情況,然後就看Row_Number()

+0

感謝您的支持。查詢按預期工作。 – VENKATESH

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 
+0

謝謝您的支持。查詢正在工作,但它提供了作業中每個步驟的狀態。我需要工作狀態而不是工作中的步驟 – VENKATESH

+1

4在sql2008中不再支持向上 – aMazing