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 [email protected]_name = @job_name;END-- Create the job from scratch:EXEC [email protected]_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 [email protected]_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 [email protected]_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 [email protected]_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, -- [email protected]_end_date = 99991231, -- YYYYMMDD (no end date)@active_start_time = 120000, -- [email protected]_end_time = 235959; -- HHMMSS