I'm trying to update a SQL report sproc's WHERE clause to check whether a given date falls on or before the next occurrence of a class. Classes have a StartDate and occur once per week on the same day each week. Given the StartDate, how can I find the next occurrence of that day of the week?
E.G. If the StartDate is 1/18/2012, a Wednesday, and I run the report as of today, 1/26/2012, I need to find 2/1/2012 which is the next Wednesday after 1/26. If the StartDate is 1/19, a Thurs, and I run the report today, the formula should give me Thurs 1/26 which is today.
Here's sort of the idea in SQL:
SELECT *
FROM tbl_Class cs
INNER JOIN tbl_Enrollment sce ON cs.pk_ClassID = sce.fk_ClassID
WHERE ...
AND sce.StartDate < [Find date of next class after #AsOfDate using cs.StartDate]
Here's some example SQL that I came up with. 3 iterations so you can follow how I got to the end. The 3rd iteration should be something you can incorporate into a WHERE clause by substituting your column names for the variables.
Setup:
DECLARE #Startdate DATETIME,#currentdate datetime
SET #Startdate = '1-26-2012'
SET #Currentdate = '1-23-2012'
--This section just normalizes it so you can use 7 as the interval
--The offset depends on your current setting for DATEFIRST, U.S. English default is 7, Sunday.
-- see http://msdn.microsoft.com/en-us/library/ms187766.aspx
DECLARE #StartDateWorkingDayOfWeek int,#CurrentDateWorkingDayOfWeek int
SELECT #StartDateWorkingDayOfWeek =(DATEPART(weekday,#Startdate)-2)
SELECT #CurrentDateWorkingDayOfWeek=(DATEPART(weekday,#Currentdate)-2)
Iteration #1
--Iteration 1
IF #StartDateWorkingDayOfWeek < #CurrentDateWorkingDayOfWeek
SELECT DATEADD(DAY,DATEDIFF(DAY,0,#Currentdate)/7*7 + 7,#StartDateWorkingDayOfWeek)
else
SELECT DATEADD(DAY,DATEDIFF(DAY,0,#Currentdate)/7*7 + 0,#StartDateWorkingDayOfWeek)
Iteration #2
--Iteration 2
SELECT DATEADD(DAY,DATEDIFF(DAY,0,#Currentdate)/7*7 +
CASE WHEN #StartDateWorkingDayOfWeek < #CurrentDateWorkingDayOfWeek
then 7
ELSE 0
end
,#StartDateWorkingDayOfWeek)
Iteration #3
--iteration 3
SELECT DATEADD(DAY,DATEDIFF(DAY,0,#Currentdate)/7*7 +
CASE WHEN (DATEPART(weekday,#Startdate)-2) < (DATEPART(weekday,#Currentdate)-2)
then 7
ELSE 0
end
,(DATEPART(weekday,#Startdate)-2))
Hat tip to this article:
http://www.sqlmag.com/article/tsql3/datetime-calculations-part-3
Here's what I came up with thanks to TetonSig and his reference to this link: http://www.sqlmag.com/article/tsql3/datetime-calculations-part-3
We can get the date of the previous Monday exclusive of the current date (#AsOfDate) like so:
SELECT DATEADD(day, DATEDIFF(day,0, #AsOfDate-1) /7*7, 0);
This gets the number of days between 1/1/1900 and #AsOfDate in days. /7*7 converts that to whole weeks, and then adds it back to 1/1/1900 (a Mon) to get the Monday before #AsOfDate. The -1 makes it exclusive of #AsOfDate. Without the minus 1, if #AsOfDate were on a Monday, it would be counted as the "previous" Monday.
Next the author shows that to get the inclusive next Monday, we simply need to add 7 to the exclusive previous Monday formula:
SELECT DATEADD(d, DATEDIFF(day,0, #AsOfDate-1) /7*7, 0)+7;
Voila! We've now got the first Monday on or after #AsOfDate. The only problem is, the Monday (0) above is a moving target in my case. I need the first [DayOfWeek] determined by the class date, not the first Monday. I need to swap out a ClassDayOfWeek calculation for the 0s above:
DATEADD(d, DATEDIFF(d, [ClassDayOfWeek], #AsOfDate-1)/7*7, [ClassDayOfWeek])+7
I wanted to calculate the ClassDayOfWeek without being dependent on or having to mess with setting ##datefirst. So I calculated it relative to the base date:
DATEDIFF(d, 0, StartDate)%7
This gives 0 for Mon, 6 for Sun so we can now plug that in for [ClassDayOfWeek]. I should point out that this 0-6 value is dates 1/1/1900-1/7/1900 represented as an int.
DATEADD(d, DATEDIFF(d, DATEDIFF(d, 0, StartDate)%7, #AsOfDate-1)/7*7, DATEDIFF(d, 0, StartDate)%7)+7
And in use per the question:
SELECT *
FROM tbl_Class cs
INNER JOIN tbl_Enrollment sce ON cs.pk_ClassID = sce.fk_ClassID
WHERE ...
AND sce.StartDate < DATEADD(d,
DATEDIFF(d,
DATEDIFF(d, 0, cs.StartDate)%7,
#AsOfDate-1)/7*7,
DATEDIFF(d, 0, cs.StartDate)%7)+7
I derived the answer with a simple case statement.
In your situation #targetDOW would be the day of the week of the class.
DECLARE #todayDOW INT = DATEPART(dw, GETDATE());
DECLARE #diff INT = (#targetDOW - #todayDOW);
SELECT
CASE
WHEN #diff = 0 THEN GETDATE()
WHEN #diff > 0 THEN DATEADD(d,#diff,GETDATE())
WHEN #diff < 0 THEN DATEADD(d,#diff + 7,GETDATE())
END;
Related
I am trying to write a SQL query that shows the count of the days and date depending upon the financial period it falls in. The financial period starts 5 days before the month end eg march 27th to 26th April
For the above mentioned period if the day is 29th march, the count of the day should be 3 and the date should be 2020-04. The date should adjust depending upon the period it falls in.
I tried to adress the second part of this query by writing the below script but it does not bring any result
declare #date datetime
set #date = getdate()
SELECT format (date,'yyyy-MM-dd') as date
where #date
between dateadd(day,-5,EOMONTH(getdate(),-1)) and dateadd(day,-5,EOMONTH(getdate()))
updated to include 5 days from previous month.
Is this what you are looking for the second part?
Edit: Modifying the query. I guess this should give you what you need for both the parts.
you can try changing the dates in set #date.
Please note that the -4 instead of -5 is done intentionally as you said the financial month starts 5 days earlier. For March, 31 - 5 would give 26, but it should start on 27 right? so that on 29th the no. of days should be 3 including 27 and 29. Anyways, the query should be self explanatory, might just need to change the number depending on your requirement.
declare #date datetime
--set #date = getdate()
set #date = '2020-02-14'
SELECT format(#date,'yyyy-MM-dd') as date,
case WHEN #date < dateadd(day,-4,EOMONTH(#date)) THEN format(EOMONTH(#date),'yyyy-MM')
ELSE format(EOMONTH(#date, 1),'yyyy-MM') END
AS FinancialMonth,
CASE WHEN #date < dateadd(day,-4,EOMONTH(#date)) THEN DATEDIFF(day,dateadd(day,-5,EOMONTH(#date,-1)), #date)
ELSE DATEDIFF(day, dateadd(day,-5,EOMONTH(#date)), #date) END
AS CountDays
The following code will calculate what you need. Please read the comments in the code itself.
-- First, lets declare all the variables we need.
-- I tried to name them so they are selfexplanatory.
declare #inputdate DateTime,
#financialPeriodStartDate DateTime,
#EndOfTheMonth DateTime,
#nextFinantialMonthYear DateTime,
#previousFinancialPeriodStartDate DateTime
-- Now we calculate some of the values
set #inputdate = GETDATE() -- Let's use Today's date, but you can change this to any date.
set #EndOfTheMonth = EOMONTH(#inputdate) -- This is the end of the month for the input date
set #financialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(#inputdate)) -- This is you Financial Period Start Date for the giving input date.
set #previousFinancialPeriodStartDate = DATEADD(DAY,-5,EOMONTH(DATEADD(MONTH, -1, #inputdate))) -- Also calculates the Start Date of the precious financial period.
set #nextFinantialMonthYear = DATEADD(MONTH, 1,#financialPeriodStartDate) -- This is the start date of the next financial period.
-- In the following Select, it calculates the values you need, based in the previous variables.
select
#inputdate as Today,
#EndOfTheMonth as EndOfMonth,
#previousFinancialPeriodStartDate as PreviousFinancialPeriodStartDate,
#financialPeriodStartDate as FinacialPeriodStartDate,
CASE WHEN DATEDIFF(DAY , #financialPeriodStartDate, #inputdate + 1 ) < 0
THEN DATEDIFF(DAY , #previousFinancialPeriodStartDate, #inputdate + 1 )
WHEN DATEDIFF(DAY , #financialPeriodStartDate, #inputdate + 1 ) >=0
THEN DATEDIFF(DAY , #financialPeriodStartDate, #inputdate + 1 )
END as DaysFromFPStartDate,
STR(YEAR(#nextFinantialMonthYear)) +'-'+LTRIM(RTRIM(STR(MONTH(#nextFinantialMonthYear)))) as NextFinantialPeriodMonthAndYear
I hope it helps.
My company groups all tasks into individual weeks that end on a Thursday. Thus a task due on 3/20/19 would be grouped into the 3/21 week and tasks due on 3/22 group into the 3/28/19 week.
I'm looking to calculate this field (called duedate_Weekdue) based on an input duedate.
The following works but doesn't seem like the simplest way to do this. Anyone have more elegant methods?
Select
getdate() as duedate,
datepart(yy,getdate()) as duedate_yr,
datepart(ww,getdate()) as duedate_ww,
CASE
When datename(dw,Dateadd(day,1,getdate()))='Thursday' Then Dateadd(day,1,getdate())
When datename(dw,Dateadd(day,2,getdate()))='Thursday' Then Dateadd(day,2,getdate())
When datename(dw,Dateadd(day,3,getdate()))='Thursday' Then Dateadd(day,3,getdate())
When datename(dw,Dateadd(day,4,getdate()))='Thursday' Then Dateadd(day,4,getdate())
When datename(dw,Dateadd(day,5,getdate()))='Thursday' Then Dateadd(day,5,getdate())
When datename(dw,Dateadd(day,6,getdate()))='Thursday' Then Dateadd(day,6,getdate())
When datename(dw,Dateadd(day,0,getdate()))='Thursday' Then Dateadd(day,0,getdate())
END as duedate_Weekdue;
You can reduce that to one line of code that uses a little math, and some SQL Engine trivia.
The answers that depend on DATEPART return non-deterministic results, depending on the setting for DATEFIRST, which tells the SQL Engine what day of the week to treat as the first day of the week.
There's a way to do what you want without the risk of getting the wrong result based on a change to the DATEFIRST setting.
Inside SQL Server, day number 0 is January 1, 1900, which happens to have been a Monday. We've all used this little trick to strip the time off of GETDATE() by calculating the number of days since day 0 then adding that number to day 0 to get today's date at midnight:
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()),0)
Similarly, day number 3 was January 4, 1900. That's relevant because that day was a Thursday. Applying a little math to the number of days, and relying on the DATEDIFF function to drop fractions, which it does, this calculation will always return the next Thursday for you:
SELECT DATEADD(DAY, (DATEDIFF(DAY, 3, GETDATE())/7)*7 + 7,3);
Credit to this answer for the assist.
So your final query comes down to this:
Select
getdate() as duedate,
datepart(yy,getdate()) as duedate_yr,
datepart(ww,getdate()) as duedate_ww,
DATEADD(DAY, (DATEDIFF(DAY, 3, GETDATE())/7)*7 + 7,3) as duedate_Weekdue;
If the first day of the week is Sunday, by using the modulo operator %:
cast(dateadd(day, (13 - datepart(dw, getdate())) % 7, getdate()) as date) as duedate_Weekdue
I also applied the casting of the result to date.
Try identifying number of day in week with DATEPART and then adding enough days to go to next thursday:
declare #dt date = '2019-03-22'
declare #weekDay int
SELECT #weekDay = DATEPART(dw, #dt)
if #weekDay <= 5
select DATEADD(day, 5 - #weekDay ,#dt)
else
select DATEADD(day, 12 - #weekDay ,#dt)
So, pilots have to get so many flight hours and flight sorties within every 6 months (semi annual) as well as every year (annual). The biggest pain is that the start and ending dates of these periods are based upon their birth month.
You can find more information about my schema here: Design decision: Table schema for partial dates in order to calculate time spans (SQL Server)
DECLARE #date Date
SET #date = '1985-04-12'
DECLARE #diffInYears INT
SET #diffInYears = DATEDIFF(yy, #date, GETDATE())
DECLARE #currentBirthDate Date
SET #currentBirthDate = (SELECT dateadd(yyyy, #diffInYears, #date))
SELECT DATEADD(dd, -DAY(DATEADD(m,1,#currentBirthDate)), DATEADD(m,7,#currentBirthDate)) semiAnnualDateEnd,
DATEADD(dd, -DAY(DATEADD(m,1,#currentBirthDate)), DATEADD(m,13,#currentBirthDate)) annualDateEnd
RESULTS:
semiAnnualDateEnd - annualDateEnd
2012-10-31 - 2013-04-30
Now, this is great, these are the dates I want for this particular example.
However, when we come to November 1st, 2012, I want the semiAnnualDateEnd to become 2013-04-30.
Also, when 2013 comes around (January 1st, 2013), the annualDateEnd is going to become 2014-04-30, when I want it to stay 2013-04-30 until 2013-05-01 comes around, and then for it to become 2014-04-30 (similar situation for the semiAnnual).
I don't want to keep these dates statically associated with a particular pilot. That is, I don't want to keep a couple fields in the Pilot table that have these. However, I want to use these for displaying and calculations. For example, going to need to display each pilot's current semiAnnual and annual sorties and flight hours, as well as displaying a snapshot their "current" stats at any particular point in time.
EDIT: I'm using SQL Server 2008 Express RC
EDIT 2: I'm thinking I should change the #currentBirthDate to (SELECT DATEADD(yyyy, #diffInYears - 1, #date). Then, I need to do a case statement below (continuing experimentation)
The rule for the semi-annual date seems to be: add five months to the month and go to the end of the month. End of the month can be a problem. So, let's change this to "add six months, got to the end of the month and subtract one day". (I am basing this logic on your example.)
The following expression does this:
select dateadd(d, -1,
cast(cast(year(bd)+(case when month(bd)+6 > 12 then 1 else 0 end) as varchar(255))+'-'+
cast(case when month(bd)+7> 12 then month(bd)+6-12 else month(bd) end as varchar(255))+'-'+
'1' as date))
from (select cast('2011-11-01' as date) bd) t
It does the date arithmetic on the year() and month() values of the date. It then gloms them back together as a string, converts to a date, and subtracts 1 day.
I think something similar will work for your year dates as well.
DECLARE #pilotID INT
SET #pilotID = 1
DECLARE #birthDate DATE
SET #birthDate = (SELECT birthDate FROM Pilot WHERE pilotID = #pilotID)
DECLARE #diffInYears INT
SET #diffInYears = DATEDIFF(yy, #birthDate, GETDATE())
DECLARE #currentBirthDate DATE
SET #currentBirthDate = (DATEADD(yyyy, #diffInYears - 1, #birthDate))
DECLARE #firstSixMonthStart DATE
DECLARE #firstSixMonthEnd DATE
DECLARE #secondSixMonthStart DATE
DECLARE #secondSixMonthEnd DATE
SET #firstSixMonthStart = (DATEADD(dd,-(DAY(DATEADD(m,1,#currentBirthDate))-1),DATEADD(m,1,#currentBirthDate)))
SET #firstSixMonthEnd = (DATEADD(dd, -DAY(DATEADD(m,1,#currentBirthDate)), DATEADD(m,7,#currentBirthDate)))
SET #secondSixMonthStart = (DATEADD(dd,-(DAY(DATEADD(m,1,#currentBirthDate))-1),DATEADD(m,7,#currentBirthDate)))
SET #secondSixMonthEnd = (DATEADD(dd, -DAY(DATEADD(m,1,#currentBirthDate)), DATEADD(m,13,#currentBirthDate)))
DECLARE #semiAnnualStart AS DATE
DECLARE #semiAnnualEnd AS DATE
DECLARE #annualStart AS DATE
DECLARE #annualEnd AS DATE
SET #semiAnnualStart = CASE
WHEN GETDATE() > (DATEADD(dd, -DAY(DATEADD(m,1,#firstSixMonthEnd)), DATEADD(m,7,#firstSixMonthEnd)))
THEN (DATEADD(yyyy, 1, #firstSixMonthStart))
WHEN GETDATE() > #firstSixMonthEnd
THEN #secondSixMonthStart
ELSE #firstSixMonthStart
END
SET #semiAnnualEnd = CASE
WHEN GETDATE() > (DATEADD(dd, -DAY(DATEADD(m,1,#firstSixMonthEnd)), DATEADD(m,7,#firstSixMonthEnd)))
THEN (DATEADD(yyyy, 1, #firstSixMonthEnd))
WHEN GETDATE() > #firstSixMonthEnd
THEN #secondSixMonthEnd
ELSE #firstSixMonthEnd
END
SET #annualStart = CASE
WHEN GETDATE() > #secondSixMonthEnd THEN (DATEADD(yyyy, 1, #firstSixMonthStart))
ELSE #firstSixMonthStart
END
SET #annualEnd = CASE
WHEN GETDATE() > #secondSixMonthEnd THEN (DATEADD(yyyy, 1, #secondSixMonthEnd))
ELSE #secondSixMonthEnd
END
SELECT #semiAnnualStart semiStart, #semiAnnualEnd semiEnd,
#annualStart annualStart, #annualEnd annualEnd,
#firstSixMonthStart firstStart, #firstSixMonthEnd firstEnd,
#secondSixMonthStart secondStart, #secondSixMonthEnd secondEnd,
COUNT(*) semiSorties, ISNULL(SUM(hours), 0) semiSortieHours
FROM PilotLog
WHERE pilotID = #pilotID
AND topLevelPosition = 'AVO'
AND flightDate BETWEEN #semiAnnualStart AND #semiAnnualEnd
RESULTS:
semiStart semiEnd annualStart annualEnd firstStart firstEnd secondStart secondEnd semiSorties semiSortieHours
2012-05-01 2012-10-31 2011-11-01 2012-10-31 2011-11-01 2012-04-30 2012-05-01 2012-10-31 1 1.7
This ended up working... Problem is, I'm going to need to do this for every pilot on the overall summary page. Additionally, I'm going to need to calculate this kind of sortie information for snapshots that she wants. She wants to go back to any particular month and see a snapshot, listing each flight as well as the sortie stats they had upon completing that flight. This SQL should work for these situations, it's just I'll have to change it up a bit here and there.
(EDIT: Why doesn't my code scroll horizontally..? I don't want it to wrap. Nevermind that's just internet explorer looks like)
I know this is quite a generic question but does anyone know a good way of checking if the date is the last monday of the month using T-SQL. I need to use it in a stored procedure to determine if the stored procedure returns data or does nothing.
Cheers!
The following select will return 1 if the current date is the last monday of the month, and 0 if not.
select
case
when datepart(dw, GETDATE()) = 2 and DATEPART(month, DATEADD(day, 7, GETDATE())) <> DATEPART(month, GETDATE())
then 1
else 0
end
datepart(dw, GETDATE()) returns the day of the week. Monday is 2. The second part adds 7 days to the current date and checks that within 7 days the month has changed (if it does not, it is not the last monday).
Change the GETDATE()'s to any date you want to check.
EDIT:
You can make it into a generic function and use it with any date you like:
CREATE FUNCTION
IsLastMondayOfMonth(#dateToCheck datetime)
RETURNS bit
AS
BEGIN
DECLARE
#result bit
SELECT #result =
CASE
WHEN datepart(dw, #dateToCheck) = 2 AND DATEPART(month, DATEADD(day, 7, #dateToCheck)) <> DATEPART(month, #dateToCheck)
THEN 1
ELSE 0
END
RETURN #result
END
Maybe something like this:
DECLARE #YourDate DATETIME='2012-02-25'
SELECT
CASE
WHEN #YourDate = DATEADD(wk, DATEDIFF(wk,0,DATEADD(month,DATEDIFF(MONTH,0,#YourDate),30)),0)
THEN 1
ELSE 0
END
Although you have already accepted another answer, an even simpler solution (in my opinion) is to use a calendar table that has a column called IsLastMondayOfMonth or something similar. Calendar tables tend to be much easier to maintain than functions because not only is the code much cleaner but also when an exception comes along ("because of an unusual public holiday this year we need to do our month-end processing one day later, I'm sure you can fix the system to do that?") you can just update a table to handle it instead of adding potentially awkward logic to your code.
This will select the date when the date is the last monday of the month regardless of firstdate. Making a function that rely on the database settings, is really not good practice.
select d
from (select '2012-02-20' d union all select '2012-02-27' union all select '2012-02-28') a
where datepart(day, dateadd(day, 7 ,d)) < 8 and datediff(day, 0, d) %7 = 0
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)
DATEADD(wk, #StartDate, #recurrenceValue1)
To find out which day of the week the date you are looking at belongs, you can use (MSDN DATEPART)
DATEPART(dw, #StartDate)
This function uses DATEFIRST to determine which day of the week is the first one (http://msdn.microsoft.com/en-us/library/ms181598.aspx)
SET DATEFIRST 1 --Where 1 = Monday and 7 = Sunday
So for your problem (DATEFIRST being set to 1 = Monday)..
SET DATEFIRST 1
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
SET #StartDate = '2011-12-16' -- This is a Friday
SET #recurrenceValue1 = 2 -- In 2 weeks
SET #recurrenceValue2 = 2 -- On Tuesday
SET #NextOcurrance = DATEADD(wk, #recurrenceValue1, #StartDate) -- Add our 2 weeks
/* Check if our incrementation falls on the correct day - Adjust if needed */
IF (DATEPART(dw, #NextOcurrance) != #recurrenceValue2) BEGIN
DECLARE #weekDay int = DATEPART(dw, #NextOcurrance)
SET #NextOcurrance = DATEADD(dd, ((7 - #weekDay) + #recurrenceValue2), #NextOcurrance) -- Add to #NextOcurrance the number of days missing to be on the requested day of week
END
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.
CREATE TABLE OccurenceExclusions (
ExclusionDate DATE not null,
NumberOfDaysToAdd int not null
PRIMARY KEY (ExclusionDate)
)
INSERT OccurenceExclusions VALUES ('2012-01-01', 7)
SET #NextOcurrance = DATEADD(dd, COALESCE((SELECT NumberOfDaysToAdd
FROM OccurrenceExclusions
WHERE ExclusionDate = #NextOcurrance), 0), #NextOcurrance)
Probably the best solution would be to use a calendar table. http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html
You could then query it like so:
SELECT TOP 1 #NextOccurance = Date
FROM CalendarTable
WHERE Date >= DATEADD(week, #recurranceValue1, #StartDate)
AND DateName = #recurranceValue2
Using the principles the #DanielM set out i changed it to fit my query see below:
BEGIN
SET DATEFIRST 1 --Where 1 = Monday and 7 = Sunday
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
-- sets #nextoccurence to next date after x amount of weeks
SET #NextOccurance = DATEADD(wk, #recurrenceValue1, #StartDate) -- Add on weeks /* Check if our incrementation falls on the correct day - Adjust if needed */
IF (DATEPART(dw, #NextOccurance) != #recurrenceValue2)
BEGIN
DECLARE #Weekday int = DATEPART(dw, #NextOccurance)
SET #NextOccurance = DATEADD(dd, (#RecurrenceValue2 - #Weekday), #NextOccurance) -- Add to #NextOcurrance the number of days missing to be on the requested day of week
END
END