Get date of last successful job run?

前端 未结 5 1282
萌比男神i
萌比男神i 2021-02-20 16:48

I have a single step job that executes a stored procedure. I would like get the date of the last successful job execution time so that I can just update a delta instead of the w

5条回答
  •  时光说笑
    2021-02-20 17:05

    The tables you want are sysjobs and sysjobhistory in msdb. Although be warned! SQL Server only maintains a certain number of records, so if there are too many jobs and the history is not large enough, you will end up with no history.

    The following code retrieves the job_id for the given job name, and queries the history table for the last successfully finished run (i.e. step 0, status 1). As you can see, you have to convert the run time back to a date, as SQL Server stores it in two int columns:

    DECLARE @job_id binary(16)
    SELECT @job_id = job_id FROM msdb.dbo.sysjobs WHERE (name = N'YourJobName')
    
    SELECT TOP 1
        CONVERT(DATETIME, RTRIM(run_date))
        + ((run_time / 10000 * 3600) 
        + ((run_time % 10000) / 100 * 60) 
        + (run_time % 10000) % 100) / (86399.9964) AS run_datetime
        , *
    FROM
        msdb..sysjobhistory sjh
    WHERE
        sjh.step_id = 0 
        AND sjh.run_status = 1 
        AND sjh.job_id = @job_id
    ORDER BY
        run_datetime DESC
    

提交回复
热议问题