Overview of SQL Jobs

Introduction

Scheduled jobs are a part of development, no matter the application. Inventory applications require the most when they automate almost everything. SQL Jobs can prove to be handy when a query needs to run and update or insert or anything of that sort at regular intervals as per requirements. These are similar to schedulers to track your reminders and updates.

According to MSDN

"SQL Server Agent is a Microsoft Windows service that executes scheduled administrative tasks, which are called jobs in SQL Server 2016".

SQL Jobs are run by the SQL Server Agents. It can be a single operation running in the background or a series of operations. The SQL Jobs can be added using the GUI provided by the SQL Server. But in this article, we will see and understand the Query that helps create SQL Jobs. These jobs can be scheduled to run daily, weekly, or on a monthly basis.

Straight to the point

We will straight away check and see the snippet and then try to understand the parts of it.

  1. BEGIN TRANSACTION;  
  2. DECLARE @ReturnCode INT;  
  3. SELECT @ReturnCode = 0;  
  4. DECLARE @owner_Login_Id NVARCHAR(30),   
  5.         @actual_database_name NVARCHAR(30);  
  6. SET @owner_Login_Id = N''-- ADD THE LOGIN NAME TO THE SERVER  
  7. SET @actual_database_name = N'DB NAME'-- ADD THE DATABASE NAME AS REQUIRED  
  8.   
  9. IF NOT EXISTS( SELECT name  
  10.                FROM msdb.dbo.syscategories  
  11.                WHERE name = N'[Uncategorized (Local)]'  
  12.                  AND category_class = 1 )  
  13.     BEGIN  
  14.         EXEC @ReturnCode = msdb.dbo.sp_add_category  
  15.              @class = N'JOB',  
  16.              @type = N'LOCAL',  
  17.              @name = N'[Uncategorized (Local)]';  
  18.         IF( @@ERROR <> 0  
  19.          OR @ReturnCode <> 0  
  20.           )  
  21.         GOTO QuitWithRollback;  
  22.     END;  
  23. DECLARE @jobId BINARY(16);  
  24. EXEC @ReturnCode = msdb.dbo.sp_add_job  
  25.      @job_name = N'JOB_NAME',  
  26.      @enabled = 1,  
  27.      @notify_level_eventlog = 0,  
  28.      @notify_level_email = 0,  
  29.      @notify_level_netsend = 0,  
  30.      @notify_level_page = 0,  
  31.      @delete_level = 0,  
  32.      @description = N'JOB_DESCRIPTION',  
  33.      @category_name = N'[Uncategorized (Local)]',  
  34.      @owner_login_name = @owner_Login_Id,  
  35.      @job_id = @jobId OUTPUT;  
  36. IF( @@ERROR <> 0  
  37.  OR @ReturnCode <> 0  
  38.   )  
  39. GOTO QuitWithRollback;  
  40.   
  41. EXEC @ReturnCode = msdb.dbo.sp_add_jobstep  
  42.      @job_id = @jobId,//-- ID of the Job created  
  43.      @step_name = N'STEP_NAME', //--Step Name for the JOB  
  44.      @step_id = 1,  
  45.      @cmdexec_success_code = 0,  
  46.      @on_success_action = 1,  
  47.      @on_success_step_id = 0,  
  48.      @on_fail_action = 2,  
  49.      @on_fail_step_id = 0,  
  50.      @retry_attempts = 0,  
  51.      @retry_interval = 0,  
  52.      @os_run_priority = 0,  
  53.      @subsystem = N'TSQL',  
  54.      @command = N'YOUR QUERY GOES HERE',  
  55.      @database_name = @actual_database_name, //--Database name is generic and defined above at the start  
  56.      @flags = 0;  
  57. IF( @@ERROR <> 0  
  58.  OR @ReturnCode <> 0  
  59.   )  
  60. GOTO QuitWithRollback;  
  61. EXEC @ReturnCode = msdb.dbo.sp_update_job  
  62.      @job_id = @jobId,  
  63.      @start_step_id = 1;  
  64. IF( @@ERROR <> 0  
  65.  OR @ReturnCode <> 0  
  66.   )  
  67. GOTO QuitWithRollback;  
  68. EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule  
  69.      @job_id = @jobId,  
  70.      @name = N'JOB_SCHEDULE_NAME',  
  71.      @enabled = 1,  
  72.      @freq_type = 4,  
  73.      @freq_interval = 1,  
  74.      @freq_subday_type = 1,  
  75.      @freq_subday_interval = 0,  
  76.      @freq_relative_interval = 0,  
  77.      @freq_recurrence_factor = 0,  
  78.      @active_start_date = 20150615,  
  79.      @active_end_date = 99991231,  
  80.      @active_start_time = 0,  
  81.      @active_end_time = 235959,  
  82.      @schedule_uid = N'af82656c-e151-4ebb-9fe1-009495e1415d';  
  83. IF( @@ERROR <> 0  
  84.  OR @ReturnCode <> 0  
  85.   )  
  86. GOTO QuitWithRollback;  
  87. EXEC @ReturnCode = msdb.dbo.sp_add_jobserver  
  88.      @job_id = @jobId,  
  89.      @server_name = N'(local)';  
  90. IF( @@ERROR <> 0  
  91.  OR @ReturnCode <> 0  
  92.   )  
  93. GOTO QuitWithRollback;  
  94. COMMIT TRANSACTION;  
  95. GOTO EndSave;  
  96. QuitWithRollback:  
  97. IF( @@TRANCOUNT > 0 )  
  98. ROLLBACK TRANSACTION;  
  99. EndSave:  
  100. GO  
The snippet part Line No. 9-12 results the existence of the local categories. What this does is simple.

image

From MSDN

"Contains the categories used by SQL Server Management Studio to organize jobs".

Now, after the check, if the category exists that governs the organization job, it then executes the pre-defined stored procedure that adds a new category sp_add_category.
  1. sp_add_category   
  2.      [ [ @class = ] 'class', ]   
  3.      [ [ @type = ] 'type', ]   
  4.      { [ @name = ] 'name' }  
Where,

 

  • class: Class governs the class i.e. may be JOB|ALERT|OPERATOR
  • @type: This specifies the type or location of the Job i.e. LOCAL|MULTI-SERVER|NONE
  • @name: Category Name that will be added
After this the Job Addition SP is executed. The parameters for the SP needs to be known and why are they added. For more information MSDN can be followed.

This SP sp_add_job simply and only adds the JOB with the specified name. For the execution of JOB and to let it execute the required process, we need to add a JOB STEP, which is created next. sp_add_jobstep does the job for us. This SP adds the specific Step to be executed or run under that JOB. The parameters here can also be referred from MSDN.
  • @command is the most important parameter here, as it's the query that will actually be executeed at intervals and fulfil your requirements.
  • @database_name is also important as this would specify on which database the query would be executed by the JOB.

We are then adding the schedule for the created job using SP sp_add_jobschedule . This SP adds the required schedule for the JOB and sets the JOB to run based on the schedule. Please refer the MSDN for more info and the parameters definition.

Conclusion

That's it folks. We have seen the simple query that once run, creates a SQL job for us that can actually execute any query on the background and make life easy.

Points of Interest

We have followed TRANSACTION in the queries in order to track the errors and if any are caused, then we can roll back the changes to avoid ambiguity. Instead of now following steps to create Jobs using the SQL Server Object Explorer, run the above query, understand the parameters once and then that's easy. Hope this helps.

References

Up Next
    Ebook Download
    View all
    Learn
    View all