Saturday, March 13, 2021

how to update execution time of sql agent scheduler using sql script

 I have come across a scenario where it required to update sql agent scheduler execution date time every month in a different  date.
We can achieve this in couple of ways.
1. We can store the execution date time in a table and fetch that value and update it.
2. We can update the date time every month by running the script manually.
Please check below the execution script.
We need to update the MSDB.DBO.sysschedules table.

--You can use other columns as per your requirement

select name,enabled,active_start_date,active_end_date,date_modified 

from MSDB.DBO.sysschedules\


Declare @dt_active_start datetime
set @dt_active_start=GETDATE() --Fetch the value from table if it stored

update MSDB.DBO.sysschedules
set active_start_date=CONVERT(char(8),@dt_active_start,112)
,enabled=1
,date_modified=GETDATE()
where name='Scheduler Name'

You can use other fields for updating as per the requirement.. 

A Cursor with the name already exists

 While executing cursor inside Stored procedure it is throwing error:

A cursor with the name 'cursorName' already exists

declare cursorName CURSOR FOR
        select ...;

    open cursorName;

        Body of cursor...
        close cursorName;
        deallocate cursorName;
This is because we are using global cursor that will be defined each time you are calling this procedure and give you the same error.

Define a local cursor. Just put the keyword LOCAL after CURSOR


This will look like


declare cursorName CURSOR LOCAL FOR
...
This will resolve the issue.