Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last 24 hour job record form msdb.dbo.sysjobhistory

I want write a query to get the last 24 hours worth of job record from the "msdb.dbo.sysjobhistory" table, but I can't get because I get the "run_date" and "run_time" columns are returned as a number. How can I convert the "run_date" and "run_time" columns into a datetime variable, and use this to get the last 24 hour job history?

like image 371
gofor.net Avatar asked Oct 09 '10 06:10

gofor.net


People also ask

What is Run_status in Sysjobhistory?

It contains the history of the SQL agent jobs that run and perform operations on the server. Each row of the table corresponds to a step in the job. There is a column in the table called run_status, that gets an integer value to indicate the outcome of the job when it completed and got written into the table.

What is run duration in Sysjobhistory?

sysjobhistory table, the duration (run_duration column) is also stored as an INT and can be very confusing when querying. It is a duration stored in HHMMSS format similar to run_time except this is a duration. As an example 2300 would be 23 minutes. 15467 would be 1 hour, 54 minutes, and 67 seconds.


2 Answers

Check out this post - it shows how to "decode" those run_date columns from sysjobhistory.

You should be able to get the entries from the last 24 hours with a query something like this:

SELECT 
    j.name as JobName, 
    LastRunDateTime = 
    CONVERT(DATETIME, CONVERT(CHAR(8), run_date, 112) + ' ' 
    + STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), run_time), 6), 5, 0, ':'), 3, 0, ':'), 121)
FROM 
    msdb..sysjobs j
INNER JOIN
    msdb..sysjobhistory jh ON j.job_id = jh.job_id
WHERE
    CONVERT(DATETIME, CONVERT(CHAR(8), run_date, 112) + ' ' 
    + STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), run_time), 6), 5, 0, ':'), 3, 0, ':'), 121) > DATEADD(HOUR, -24, GETDATE())
like image 53
marc_s Avatar answered Sep 21 '22 16:09

marc_s


For databases after 2000, there is a function in the msdb database you can call that will return datetime:

msdb.dbo.agent_datetime(run_date, run_time) as 'RunDateTime'

If you are using sql 2000, you can copy the source of that function from a later version and create it in your instance of 2000. I wish I could take credit for all of this, but I originally found it here: mssqltips.com

like image 33
jj. Avatar answered Sep 23 '22 16:09

jj.