SQL Server – Datepart Logic for Custom SQL Agent Job Schedule

sql serversql-server-agent

Wanted help in code for below logic.

  1. Job A needs to be run on 8th of month.
  2. Job B needs to be run on Tuesday only.
  3. Job c needs to be run on Daily(Minus Tuesday & Sunday).
    And If Its Tuesday and 8Th Job A takes the precedence of Job.

i have coded logic for half of it.

Else If Begin logic,

--Tuesday Logic(0=Monday,1=Tuesday,2=Wed,3=Thu,4=Friday,5=Saturday,6=Sunday)
IF (SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE())/7*7,0) + 1)=1 -- If it is tuesday execute the Weekly+Daily Job
       Print 'executing weekly and daily tables'

ELSE
BEGIN
       Print 'executing daily job'
END
END

Best Answer

Here is my logic:

BEGIN
--FULL REFRESH Cycle
declare @EightDayofMonth datetime =(DATEADD(DAY, 8-DAY(GETDATE()), CONVERT(date, GETDATE())));
declare @actuladayofmonth datetime = CONVERT(date, getdate());

----checking for 8th day --condition 1 ( 8th of month and NOT Tuesday and not sunday) if any other day job executes
IF (@actuladayofmonth=@EightDayofMonth) AND (DATEPART(WEEKDAY,GETDATE())<>3 OR DATEPART(WEEKDAY,GETDATE())<>1)

BEGIN
Print 'disabe daily job'
print 'executing full job'
    END

--checking for monthly 8th is tuesday logic
ELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=3
BEGIN

Print 'Disable Tuesday Weekly'
print 'Disable Daily on tuesday'
Print 'Executing full job'
    END

ELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=1
BEGIN
Print 'Execute disable sunday'
 END
  END