开发者

Find the first, second, etc. day of week in SQL Server

开发者 https://www.devze.com 2023-03-14 12:37 出处:网络
I have a database schema to create reminders very similar to Outlook. You can create Weekly, Monthly and Yearly reminders.

I have a database schema to create reminders very similar to Outlook. You can create Weekly, Monthly and Yearly reminders.

I need to be able to find something like:

The first Friday of January
The third Wednesday of every 3 months.

Can anyone tell me how to find something like the first, second, third, fourth, etc.开发者_如何学JAVA date in SQL Server 2008?


Use datepart to find out the day of week for the first day of the month:

datepart(weekday, '2011-06-01')

From that you can calculate the first of any weekday, for example the first Monday (2):

(2 + 7 - datepart(weekday, '2011-06-01')) % 7 + 1

To get the second monday you just add 7 to that, and so on.

To check if the date is still within the same month you would need the last date of the month, which you can get by subtracting a day from the first day of the next month:

datepart(day, dateadd(day, -1, '2011-07-01'))
0

精彩评论

暂无评论...
验证码 换一张
取 消