Previous Monday & previous Sunday's date based on today's date

后端 未结 6 1550
情话喂你
情话喂你 2020-12-05 00:46

I need the correct syntax to give me :

  1. Previous week\'s Monday\'s date based on the current date/time using GETDATE()
  2. Previous week\'s Su
6条回答
  •  广开言路
    2020-12-05 01:15

    Even better, I think, this works for any date, any week day, with any DateFirst parameter (set the first day of the week, generally 1-Monday in France, default is 7-Sunday).

    create function [dbo].[previousWeekDayDate](@anyDate date, @anyWeekDay int)
    returns Date
    as
    begin
        return DATEADD(dd, ((DATEPART(dw,@anyDate) + @@DateFirst - @anyWeekDay + 13) % 7) * -1, @anyDate)
    end
    

    works for SQL 2008, create the function and use:

    SELECT dbo.previousWeekDayDate(GetDate(),1) --for Monday
    SELECT dbo.previousWeekDayDate(GetDate(),7) --for Sunday
    

提交回复
热议问题