Share via

replacing time delay

oly 66 Reputation points
2022-04-29T18:03:19.53+00:00

Hello Experts;

I have a stored procedure which is used to run a job. However, within my stored procedure I have an sql query which is used to get the status of the job, how can I make sure the job is completed first before the sql statement is ran. My code is structured as the following below

create procedure dbo.sprun_job(@Arjun singh _p varchar(45) out)
with execute as a caller
as execute as login = N'testuser'

exec msdb.dbo.msdbsprun_job
revert;

waitfor delay '00:00:30';

set @Arjun singh _p = (select run_status from msdb.dbo.sysjobhistory b)

if the waitfor delay is not there, it will say the job is still running, hence i want to make sure they job is done running before the run_status gets stored in info_p

How do I ensure that?

Thanks in advance

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

4 answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,906 Reputation points
    2022-04-29T18:13:25.273+00:00

    Was this answer helpful?

    1 person found this answer helpful.

  2. Tom Phillips 17,786 Reputation points
    2022-05-02T14:41:39.843+00:00

    If all your Agent job is doing is running an SSIS package, you can do that directly from your proc and wait for it to finish.

    See:
    https://masudprogrammer.wordpress.com/2016/08/31/ssis-execute-a-pacakge-and-wait-until-package-execution-finished/

    Was this answer helpful?

    0 comments No comments

  3. CathyJi-MSFT 22,426 Reputation points Microsoft External Staff
    2022-05-02T10:06:53.657+00:00

    Hi @oly ,

    Please check if below thread could give some idea, hope this could help you.

    sp_start_job wait for job to finish


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Was this answer helpful?

    0 comments No comments

  4. Erland Sommarskog 134.3K Reputation points MVP Volunteer Moderator
    2022-04-29T21:18:06.373+00:00

    Obviously, you will need to wait a while. And then you may have wait a while again. And again. A job could run for hours... So for a simple solution, you would need to poll it.

    But that brings up the question: why do you want to this is the first place? If you want to wait for the result, why not run the action directly in your stored procedure? Why involve a job and make things complicated?

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.