Powershell run SQL job, delay, then run the next one

前端 未结 4 1112
南旧
南旧 2021-01-22 19:40

I am writing a Powershell script that does several things with a local SQL Server database.

One thing I am doing is running several SQL jobs, one after another. I run t

4条回答
  •  星月不相逢
    2021-01-22 19:53

    My suggestion would be to wrap your job in a new sproc that starts the job then waits for it to finish by continually polling its status. From the attached article, you can do something like this:

    DECLARE @JobStatus INT
    SET @JobStatus = 0
    EXEC MSDB.dbo.sp_start_job @Job_Name = 'JobName'
    SELECT @JobStatus = current_execution_status  FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 
                              'EXEC MSDB.dbo.sp_help_job @job_name = ''JobName'', @job_aspect = ''JOB'' ')     
    WHILE @JobStatus <> 4
    BEGIN   
        SELECT @JobStatus = current_execution_status  FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 
                                    'EXEC MSDB.dbo.sp_help_job @job_name = ''JobName'', @job_aspect = ''JOB'' ')    
    END
    

    Then, rather than calling sp_start_job from the command line, call your sproc from the command line and PowerShell will be blocked until that sproc finishes. Hope this helps!

提交回复
热议问题