devxlogo

Create and Schedule an SQL Job

Create and Schedule an SQL Job

Sometimes you will have a situation where you would want a certain query, or Stored Procedure to be repeated on a daily, weekly or monthly basis (or any time increment for that matter). The most appropriate task to do is to create an SQL Job and schedule it. The next code segment, checks if an instance of the job already exists, if it does, removes it and creates a new job from scratch. Then it adds the job to the desired server and sets up how the job should be scheduled and what should happen if the job fails:

DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);SET @job_name = N'RunSampleJob';SET @description = N'Example creation of a Job';SET @owner_login_name = N'YOUR_SQL_LOGIN_NAME';SET @database_name = N'DATABASE_NAME';-- Delete job if Job already exists:IF EXISTS(SELECT job_id FROM dbo.sysjobs WHERE (name = @job_name))BEGINEXEC dbo.sp_delete_job@job_name = @job_name;END-- Create the job from scratch:EXEC dbo.sp_add_job@job_name = @job_name,@enabled = 1,@notify_level_eventlog = 0,@notify_level_email = 2,@notify_level_netsend = 2,@notify_level_page = 2,@delete_level = 0,@description = @description,@category_name = N'[Uncategorized (Local)]',@owner_login_name = @owner_login_name;-- Specify server:EXEC dbo.sp_add_jobserver @job_name = @job_name;-- Add step to job:EXEC dbo.sp_add_jobstep@job_name = @job_name,@step_name = N'Execute SQL',@step_id = 1,@cmdexec_success_code = 0,@on_success_action = 1,@on_fail_action = 2,@retry_attempts = 0,@retry_interval = 0,@os_run_priority = 0,@subsystem = N'TSQL',@command = N'YOUR QUERY HERE',@database_name = @database_name,@flags = 0;-- Update job to set start step:EXEC dbo.sp_update_job@job_name = @job_name,@enabled = 1,@start_step_id = 1,@notify_level_eventlog = 0,@notify_level_email = 2,@notify_level_netsend = 2,@notify_level_page = 2,@delete_level = 0,@description = @description,@category_name = N'[Uncategorized (Local)]',@owner_login_name = @owner_login_name,@notify_email_operator_name = N'',@notify_netsend_operator_name = N'',@notify_page_operator_name = N'';-- Schedule job:EXEC dbo.sp_add_jobschedule@job_name = @job_name,@name = N'Daily',@enabled = 1,@freq_type = 4,@freq_interval = 1,@freq_subday_type = 1,@freq_subday_interval = 0,@freq_relative_interval = 0,@freq_recurrence_factor = 1,@active_start_date = 20171010, -- YYYYMMDD@active_end_date = 99991231, -- YYYYMMDD (no end date)@active_start_time = 120000, -- HHMMSS@active_end_time = 235959; -- HHMMSS
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist