Need to have a stored procedure that calls a SQL Server Agent Job and returns whether or not the job ran successfully or not.
So far I have
CREATE PROCEDURE MonthlyData
AS
EXEC msdb.dbo.sp_start_job N'MonthlyData'
WAITFOR DELAY '000:04:00'
EXEC msdb.dbo.sp_help_jobhistory @job_name = 'MonthlyData'
GO
Which starts the job, whats the best way to get back if the job ran successfully or not?
Ok made an edit and used WAITFOR DELAY as the job normally runs between 3-4 mins never longer than 4. Does the job but is there a more efficient way to do it?
Here is a a script that will check the status of a job and will run it if it is not running already.
You can run the query:
It'll return a column run_status. Statuses are:
More info on MSDN
EDIT: You might want to to poll your job and make sure it's executed. You can get this information from sp_help_job procedure. When this procedure returns status of
4
it means the job is idle. Then it's safe to check for it's run status.You can poll using following code:
This code will check for the status, wait for 3 seconds and try again. Once we get status of 4 we know the job is done and it's safe to check for the job history.
For all you guys who are not allowed to use the OPENROWSET command, this might help. I found the start for my solution here:
http://social.msdn.microsoft.com/Forums/en-US/89659729-fea8-4df0-8057-79e0a437b658/dynamically-checking-job-status-with-tsql
This relies on the fact that some columns of the msdb.dbo.sysjobactivity table first get populated after the job finishes in one way or the other.
You might want to put in some checks for how long the WHILE-loop is allowed to run. I chose to keep that part out of the example.
Microsoft guidance for exit codes etc.: http://technet.microsoft.com/en-us/library/ms174997.aspx
I might be a bit late but I found that the following query worked for me. It will give execution time and execution end time. You can alter it to get status as well.