Dynamically getting the execution status of a SQL Server Agent Job
23 Friday Apr 2010
Written by Ranjith in T-SQL
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
execute msdb..sp_help_job
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’)
The OPENROWSET is one of the workarounds for the nested INSERT EXEC problem and many other solutions are proposed here (Thanks to Kalman for the workarounds).
Hope it helps
– Ranjith
6 comments
Swapna said:
June 4, 2010 at 12:22 pm
This was a good realization for me while struggling to get job specifics.
Only issue was that, it needed ‘Ad Hoc Distributed Queries’ to be set on the server, which needed a little fight as it is disabled by default – due to security reasons.
dan said:
August 7, 2011 at 1:34 am
Brilliant!
Augustina said:
January 27, 2016 at 2:00 pm
That hits the target dead centre! Great answer!
Jaimee Rimbach said:
May 17, 2012 at 5:03 am
Lightening up the colors a bit more would make this background perfect.
Anil said:
June 5, 2012 at 3:58 pm
Thanks for the solution. It worked for me.
Maysarah said:
November 7, 2012 at 7:46 am
Thank you.. I’ve seen so many stored procedures on the web, but this is the easiest and most creative code