sqlsql-serversql-server-2008t-sqljobs

Executing SQL Server Agent Job from a stored procedure and returning job result


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?


Solution

  • You can run the query:

    EXEC msdb.dbo.sp_help_jobhistory 
        @job_name = N'MonthlyData'
    

    It'll return a column run_status. Statuses are:

     0 - Failed
     1 - Succeeded
     2 - Retry
     3 - Canceled         
    

    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:

    DECLARE @job_status INT
    SELECT @job_status = current_execution_status FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;','exec msdb.dbo.sp_help_job @job_name = ''NightlyBackups''')
    
    WHILE @job_status <> 4
    BEGIN
        WAITFOR DELAY '00:00:03'
        SELECT @job_status = current_execution_status FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;','exec msdb.dbo.sp_help_job @job_name = ''NightlyBackups''')
    END
    
    EXEC msdb.dbo.sp_help_jobhistory 
        @job_name = N'NightlyBackups' ;
    GO
    

    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.