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

后端 未结 7 1324
青春惊慌失措
青春惊慌失措 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:48

    Try this: This will give the date for required weekday in a month.

     declare @monthstartdate date='2020-01-01',@monthenddate date='2020-01-31',@weekday char(9)='thursday',@weeknum int=4
    
            ; with cte(N,WeekDayName_C,Date_C) as
            (select 1,datename(WEEKDAY,@monthstartdate),@monthstartdate
            union all
            select n+1,datename(WEEKDAY,dateadd(day,n,@monthstartdate)),dateadd(day,n,@monthstartdate) from cte where n<31 and Date_C<=@monthenddate )
            select * from (select *,ROW_NUMBER() over (partition by WeekDayName_C order by Date_C asc)Weeknum from cte)a
            where WeekDayName_C=@weekday and Weeknum=@weeknum
    

提交回复
热议问题