Sql-server – Calling a SQL Server job within another job

jobssql-server-2008-r2

Is it possible to call a SQL Server job to run within another job?

I know we can add all steps of Job 1 to Job 2, but I prefer not to do that. First the Job 2 is already quite big and second I couldn't find a copy-paste option to copy steps between jobs, so it would be time consuming to add the steps manually.

Any suggestion is appreciated.

Best Answer

  • Right click on the job whose steps you want to add and choose "Script Job As->Create to new query window", in the resulting script look for all sections that have this format
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'<stepname>', 
  @step_id=1, 
  @cmdexec_success_code=0, 
  @on_success_action=3, 
  @on_success_step_id=0, 
  @on_fail_action=2, 
  @on_fail_step_id=0, 
  @retry_attempts=0, 
  @retry_interval=0, 
  @os_run_priority=0, @subsystem=N'TSQL', 
  @command=N'<code>', 
  @database_name=N'', 
  @flags=0
  • Open a new query window and run this:
DECLARE @jobId BINARY(16)
    SET @jobId = (SELECT job_id FROM msdb.dbo.sysjobs WHERE name = '<job name, to which you want to copy the steps>')

-- Followed by all the msdb.dbo.sp_add_jobstep from the script that scripted out in the earlier step

    EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'<stepname>', 
      @step_id=1, 
      @cmdexec_success_code=0, 
      @on_success_action=3, 
      @on_success_step_id=0, 
      @on_fail_action=2, 
      @on_fail_step_id=0, 
      @retry_attempts=0, 
      @retry_interval=0, 
      @os_run_priority=0, @subsystem=N'TSQL', 
      @command=N'<code>', 
      @database_name=N'', 
      @flags=0