I've been asked for an T-SQL challenge, I need to get the equivalent day on next month based on day position like this:
Today is 18/07/2011 in other words is the third Monday of this month...
Now I need to get the third Monday of next month (15/08/2011) on a SQL Server query.
This is like google calendar's recurrence rules.
I've been trying a lot of formulas but it gets very complicated, any help would be really appreciated.
Take a look at the example: SELECT DATENAME(WEEKDAY, '2022-01-01' ); The result is 'Saturday'. There is also an alternative method to get a day name using the function FORMAT() .
SQL Server DAY() Function The DAY() function returns the day of the month (from 1 to 31) for a specified date.
Option 2: Monday as the First Day of the WeekSELECT DATEADD(week, DATEDIFF(week, 0, RegistrationDate - 1), 0) AS Monday; In the expression above, we add the specified number of weeks to the 0 date.
In SQL Server, there is a @@DATEFIRST function, which returns the current week start day (value of SET DATEFIRST). To change default week start day, we can set any week start day value between 1-7 to DATEFIRST. @@DATEFIRST is local to the session.
This syntak will calculate the same day next week and put in null if it doesn't exists
declare @t datetime
set @t = '2008-01-29'
select case (datepart(day, @t)+ 6) / 7
when (datepart(day, @t + 28)+ 6) / 7 then @t + 28
when (datepart(day, @t + 35)+ 6) / 7 then @t + 35
else null end
CREATE FUNCTION fnSameDayOfWeekNextMonth (@Date datetime)
RETURNS datetime
AS BEGIN
RETURN (
SELECT
DATEADD(WEEK,
CASE (MONTH(ApproxDate) - MONTH(@Date) + 12) % 12
WHEN 2 THEN -1
ELSE ThisDayNum - (DAY(ApproxDate) - 1) / 7
END,
ApproxDate)
FROM (
SELECT
ThisDayNum = (DAY(@Date) - 1) / 7,
ApproxDate = DATEADD(WEEK, 5, @Date)
) s
)
END
This function implements the following logic:
Get an approximate date as the given date plus exactly 5 weeks.
Get the number of the day of the week in the given date's month.
If the month of the approximated date is 2 months after the given date's month, subtract one week from the approximated date and return the result.
Otherwise get the same as #2, but for the approximated date (instead of the given date).
Get the difference between #2 and #4.
Subtract #5, as the number of weeks, from the approximated date and return the result.
The Step #3 means that if the current date is a fifth something, then the resulting date will be the fourth same weekday of the following month, because the fifth one will be impossible. Update: @t-clausen.dk has offered, in my opinion, a better idea of returning NULLs in such cases. The above function can be easily modified to follow the same convention: the …WHEN 2 THEN -1…
part should simply be changed to …WHEN 2 THEN NULL…
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With