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

前端 未结 3 865

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\"

相关标签:
3条回答
  • 2021-01-05 06:37

    A co-worker of mine pointed out that the other given solutions only find jobs that we're started 24 hours ago (or less), not jobs that were completed 24 hours ago (or less). He proposed something along the lines of the following to location completed jobs:

    SELECT j.name AS JobName
        ,LastCompletedDateTime = DATEADD(day, (run_duration / 240000), CONVERT(DATETIME, msdb.dbo.agent_datetime(run_date, run_time))) + 
            STUFF(STUFF(REPLACE(STR((run_duration % 240000), 7, 0), ' ', '0'), 4, 0, ':'), 7, 0, ':')
    FROM msdb..sysjobs j
    INNER JOIN msdb..sysjobhistory jh ON j.job_id = jh.job_id
    WHERE DATEADD(day, (run_duration / 240000), CONVERT(DATETIME, msdb.dbo.agent_datetime(run_date, run_time))) + 
        STUFF(STUFF(REPLACE(STR((run_duration % 240000), 7, 0), ' ', '0'), 4, 0, ':'), 7, 0, ':') > DATEADD(HOUR, - 24, GETDATE())
    

    I believe part of this comes from a blog, but we cannot locate it, when I do I'll link that as well...

    0 讨论(0)
  • 2021-01-05 06:45

    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

    0 讨论(0)
  • 2021-01-05 06:50

    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())
    
    0 讨论(0)
提交回复
热议问题