SQL Source Control 7

Create SQL Server Agent job

Post-Deployment script to create a SQL Server Agent job

  1. IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE name = N'NightlyIndexRebuilds')
  2. BEGIN
  3. PRINT N'Adding SQL Server Agent job NightlyIndexRebuilds'
  4. EXEC sp_executesql N'USE msdb;
  5. EXEC dbo.sp_add_job
  6. @job_name = N''NightlyIndexRebuilds'''
  7. END
  8. GO
  9.  
  10. IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobsteps
  11. WHERE step_name = N'RebuildIndices'
  12. AND job_id = (SELECT job_id FROM msdb.dbo.sysjobs WHERE name = N'NightlyIndexRebuilds'))
  13. BEGIN
  14. PRINT N'Adding SQL Server Agent job step RebuildIndices to job NightlyIndexRebuilds'
  15. EXEC sp_executesql N'USE msdb;
  16. EXEC dbo.sp_add_jobstep
  17. @job_name = N''NightlyIndexRebuilds'',
  18. @step_name = N''RebuildIndices'',
  19. @subsystem = N''TSQL'',
  20. @command = N''EXEC sp_example_sproc_to_rebuild_indices'',
  21. @retry_attempts = 5,
  22. @retry_interval = 5'
  23. END
  24. GO

Notable points:

  • Post-Deployment scripts must be re-runnable as they will be executed as part of every deployment.
    • Object existence checks are used for both NightlyIndexRebuilds and RebuildIndices to ensure they are not created twice.
  • Post-Deployment scripts are deployed to every environment.
  • By default there is no error handling.

Didn't find what you were looking for?