SQL Server : get next relative day of week. (Next Monday, Tuesday, Wed…)

后端 未结 7 1191
青春惊慌失措
青春惊慌失措 2020-12-05 07:52

What I need is a date for the next given day (Monday, Tuesday, Wed...) following today\'s date.

The user is allowed to select what day following they want and that i

相关标签:
7条回答
  • 2020-12-05 08:51

    A calendar table is an alternative to using a bunch of date functions and date arithmetic. A minimal calendar table for this particular problem might look something like this.

    2013-09-20  Fri
    2012-09-21  Sat
    2012-09-22  Sun
    2012-09-23  Mon
    2012-09-24  Tue
    ...
    

    So a query to get the next Monday might look like this.

    select min(cal_date)
    from calendar
    where cal_date > current_date
      and day_of_week = 'Mon';
    

    In practice, you'll probably want a lot more columns in the calendar table, because you'll find a lot of uses for it.

    Also, code that uses a calendar table can usually be seen to be obviously correct. Reading the code above is simple: select the minimum calendar date that's after today and that falls on Monday. It's pretty rare to see code that relies on date functions and date arithmetic that's obviously correct.

    A calendar table in PostgreSQL

    0 讨论(0)
提交回复
热议问题