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

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

    I made this as a function, in which the procedure uses available streamlined knowledge thus it's, I think, a robust solution.

    CREATE FUNCTION [nilnul.time_._dated.date].[NextWeekday]
    (
        @nextWeekDay int  -- sunday as firstday is 1.
    )
    RETURNS datetime
    AS
    BEGIN
    
    
    declare @time datetime;
    set @time=getdate();
    
    declare @weekday int;
    set @weekday = datepart(weekday,  @time) ;
    
    declare @diff int;
    set @diff= @nextWeekDay-@weekday;
    
    --modulo 7 bijectively
    declare @moduloed int;
    set @moduloed = case 
        when @diff <=0 then @diff+7 
        else @diff
    end;
    
    return dateadd(day, @moduloed,  @time);
    
    END
    

提交回复
热议问题