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 whole set of data.
Right now I have the job setup to run once every day, so I have a default parameter that if it's null I set it to GETDATE() - 1 so I'm still updating a delta but what I'd like to do is set the date to the last successful execution of the job.
exec dbo.usp_UpdateFrom @LastSuccessfulExecutionTime
Current procedure is something like
CREATE PROCEDURE dbo.usp_UpdateFrom
@FromDate datetime = NULL --would like to pass last successful execution time of the job
AS
IF @FromDate IS NULL
SET @FromDate = GETDATE() - 1
-- do stuff
END
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:Using information from the following threads:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=112427 http://www.sqlservercentral.com/Forums/Topic542581-145-1.aspx
This is what I came up with...
I'm not particularly comfortable with this, but I prefer this method of getting the job_id over depending on the job name.
Since
sysjobhistory
only maintains a certain number of records, I recomend usingsysjobactivity
, which keeps the last execution "history" of each job and session.NOTE: If a Job has not been executed during the life of a session, almost all values will be
null
.ALSO there is a system Stored Procedure
sp_help_job
that returns this information. It acceptsjob_id
,enabled
, etc. as parameters to return 1 or more records.Have a look at this article, it may point you in the right direction. Unfortunately I don't have SQL Server on my home machine so can't test it out for you!
You basically need to query the sysjobactivity table and get the values from start_execution_date and stop_execution_date. You'll need the job_id, but i'm not sure where you'll get that from.
I hope this helps.
EDIT Ok, I've done some more research and found the following code snippet
To get Last successfully run jobs: