Brian Hansen has a stored procedure which can help you synchronize those asynchronous SQL Agent job calls:
This is a stored procedure that I have found useful in a number of circumstances. It came into being because there are times that I need to run a job via T-SQL and wait for it to complete before continuing the script. The problem is that sp_start_job
does just what it says: it starts the job and then immediately continues. There is no option to wait for it to finish.
I needed some way to pause script execution pending the completion (hopefully successfully) of the job.
One important note: this procedure using the undocumented xp_sqlagent_enum_jobs
system procedure. While this has been around for ages, it is unsupported. I get why may bother some, but this procedure is the only way that I know of to reliably determine the current run status of a job.
Read on to learn more about the procedure and grab a copy.