Wednesday, July 25, 2007

SQL Server: Executing Jobs Synchronously

SQL Server jobs can be started from T-SQL using msdb.dbo.sp_start_job:

EXEC msdb.dbo.sp_start_job @job_name = 'My job name'

This call however will return immediately (i.e. the job executes asynchronously). Sometimes it is desirable for the job to be executed synchronously.  The following procedure accomplishes this.

Usage

Parameters:

  • @jobID UNIQUEIDENTIFIER (optional, only required if @jobName is not provided)
  • @jobName NVARCHAR(500) (optional, only required if @jobID is not provided)
  • @timeoutSeconds INT (optional, default 60 seconds)

Remarks:

  • The procedure will throw an error if the timeout period is reached before the job completes
  • The procedure will throw an error if the job fails

Examples:

EXEC common.dbo.execute_job_synchronously '2696980E-1E38-43C4-8350-29DBFC56974D', null, 30

EXEC common.dbo.execute_job_synchronously null, ‘My cool job’

EXEC common.dbo.execute_job_synchronously null, ‘My cool job’, 3600

Thursday, July 05, 2007

PONG