I am trying to create a query that will bring the last STATUS of a JOB_ID, this would be simple in SQL Server 2008 using the rank over partition function, but on SQL Server 2000 this function is not available. I have managed to put the job history in order by Job_ID ascending and DATETIME descening in a temporary table ( #JOB_HISTORY -note that the pk_ID is generated in the temporary table using: IDENTITY(int, 1,1)
), but here is the part where I got stuck, I dont know how to rank the records in this table.
SELECT
h1.pk_ID,
h1.Job_ID,
h1.Status,
h1.DATETIME
FROM #JOB_HISTORY h1
ORDER BY h1.pk_ID ASC;
#JOB_HISTORY RESULT:
pk_ID, Job_ID, STATUS, DATETIME
1 1234 Succeded. 2015-03-30 12:10
2 1234 Failed. 2015-03-30 01:00
3 1234 Failed. 2015-03-28 01:00
4 5678 Failed. 2015-04-02 04:00
5 5678 Succeded. 2015-04-01 04:00
6 5678 Succeded. 2015-03-31 04:00
DESIRED OUTPUT:
Job_ID STATUS DATETIME
1234 Succeded. 2015-03-30 12:10
5678 Failed. 2015-04-02 04:00
SQL Server has freedom to insert records in any order it wants, so I wouldn't trust IDENTITY(int, 1,1)
to always give you the right sequence. It may work in some versions though.
You could inner join a sub query where you get the max datetime (or min pk_ID) to get the first/last rows. Here's a working example for getting the last outcome of each job in SQL Server 2000:
use msdb;
select
sysjobhistory.job_id as job_id
-- https://msdn.microsoft.com/en-us/library/ms174997.aspx
, case sysjobhistory.run_status
when 0 then 'Failed'
when 1 then 'Succeeded'
when 2 then 'Retry'
when 3 then 'Canceled'
else cast(sysjobhistory.run_status as varchar(10))
end as run_status
, jobLastHistory.lastDateTime as execution_time
FROM dbo.sysjobhistory as sysjobhistory
inner join (
--last datetime for each job_id
SELECT
history.job_id
, max( --newest
CONVERT(DATETIME, STUFF(STUFF(STUFF( --yyyymmddhhmiss --> datetime
cast(history.run_date as varchar(8))--yyyymmdd
+right('000000'+cast(history.run_time as varchar(8)),6) --hhmiss
,13,0,':'),11,0,':'),9,0,' '))
) AS lastDateTime
FROM dbo.sysjobhistory as history
where history.step_id = 0 --job outcome
group by
history.job_id
) as jobLastHistory
on jobLastHistory.job_id
= sysjobhistory.job_id --same job
and convert(varchar(8),jobLastHistory.lastDateTime,112)
= sysjobhistory.run_date --latest date (yyyymmdd)
and replace(convert(varchar(8),jobLastHistory.lastDateTime,108),':','')
= sysjobhistory.run_time --latest time (hhmiss)
where sysjobhistory.step_id = 0 --job outcome
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.