Dynamically getting the execution status of a SQL Server Agent Job
23 Friday Apr 2010
This problem seems trivial but there is no straight forward way to get this information. If you have tried the INSERT into EXEC command to insert the results of the sp_help_job procedure into a temporary table like below then you are familiar with the below error.
insert into #jobstatus
Msg 8164, Level 16, State 1, Procedure sp_get_composite_job_info, Line 72
An INSERT EXEC statement cannot be nested.
So you can not directly insert the results to a temp table from this procedure. Here is a trick I have used using the OPENROWSET to get around with the INSERT EXEC problem. This query results can be stored into a temporary table or a table variable using the INSERT INTO or SELECT INTO command which can be used for further processing.
select name, case when current_execution_status = 1 then ‘Executing’
when current_execution_status = 2 then ‘Waiting For Thread’
when current_execution_status = 3 then ‘Between Retries’
when current_execution_status = 4 then ‘Idle’
when current_execution_status = 5 then ‘Suspended’
when current_execution_status = 6 then ‘[Obsolete]’
when current_execution_status = 7 then ‘PerformingCompletionActions’
else NULL end as [status] from
openrowset(‘SQLNCLI’, ‘Server=(local);Trusted_Connection=yes;’,‘EXEC msdb..sp_help_job’)
Hope it helps