I’m trying to write a sql query which depending on what the user selects will recur every x day every x weeks.
So the user will select that they want the job to recur on tuesdays every 2 weeks
the values that are supplied are
declare @StartDate datetime -- when the job first recurs
declare @recurrenceValue1 int -- amount of weeks
declare @recurrenceValue2 int -- day of week (mon-sun)
declare @NextOcurrance datetime -- when the job will recur
I know how to set it for the amount of weeks:
SET @NextOccurance = (Convert(char(12),@StartDate + (@RecurrenceValue1),106))
But I’m not sure how to make it roll on to the day of the week so if the @startDate is today and it should recur every 2 weeks on a tuesday it will see that 2 weeks today is wednesday so will loop until it know that the day is tuesday and that will be the @NextRecurrance date.
Thanks in advance
An easy way to add a number of weeks to a date is to use (MSDN DATEADD)
To find out which day of the week the date you are looking at belongs, you can use (MSDN DATEPART)
This function uses DATEFIRST to determine which day of the week is the first one (http://msdn.microsoft.com/en-us/library/ms181598.aspx)
So for your problem (DATEFIRST being set to 1 = Monday)..
The logic for the number of days to add is as follow:
We have 7 days in a week, how many days does it take to reach the end of this week. Add this number of days to the @recurrenceValue2 (day of week we are looking for).
PS: I can’t post more than 2 HyperLinks because of my reputation. This is why the DATEFIRST URL is in plain text.
Here’s some code to allow certain specific date to be handled differently. Though this code is good only for unique dates. If ones needs to skip an entire week for instance, using this code will require to add values for each day of this week to skip. For ranges other than unique days, this code should be modified to handle date ranges or specific weeks and/or day of week.