T-SQL DateMath: for any given date, find occurrence of the dayname in month, e.g. 3rd Saturday

StackOverflow https://stackoverflow.com/questions/13713692

Pregunta

I am trying to develop a scheduling application that needs to represent rules such as "this event occurs on the 2nd and 4th Wednesdays of the month" or "this event happens on odd-numbered Saturdays of the month (i.e. the 1st, 3rd, and 5th Saturday).

To that end, I need to write a function in T-SQL that takes a Date input and returns an integer representing which occurrence-in-month of the dayname falls on that date.

For example, if I send the function 2012 DEC 21, it would return 3, because December 21, 2012 falls on the 3rd Friday of that month. Given 2012 DEC 29, it would return 5, since December 29, 2012 falls on the 5th Saturday of that month.

I'd like to do this without recourse to a prepopulated calendar table. I might want to use the function to work with historical dates, e.g. to compute which Wednesday of the month July 16, 1958 was.

¿Fue útil?

Solución

Try this:

SELECT ((DATEPART(d, @input) - 1) / 7) + 1

We don't care about the actual day of the week, just the number of days past the first of the month (which is the day value - 1). Then an integer divide by 7 to get the number of weeks past the first of the month, and finally + 1 to have it start at 1 instead of 0.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top