How to get Previous business day in a week with that of current Business Day using sql server

后端 未结 8 2076
情歌与酒
情歌与酒 2020-12-14 09:00

i have an ssis Package which runs on business days (mon-Fri). if i receive file on tuesday , background(DB), it takes previous business day date and does some transactions.

相关标签:
8条回答
  • 2020-12-14 09:57
    SELECT  DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE()) 
                            WHEN 'Sunday' THEN -2 
                            WHEN 'Monday' THEN -3 
                            ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
    

    I prefer to use DATENAME for things like this over DATEPART as it removes the need for Setting DATEFIRST And ensures that variations on time/date settings on local machines do not affect the results. Finally DATEDIFF(DAY, 0, GETDATE()) will remove the time part of GETDATE() removing the need to convert to varchar (much slower).


    EDIT (almost 2 years on)

    This answer was very early in my SO career and it annoys me everytime it gets upvoted because I no longer agree with the sentiment of using DATENAME.

    A much more rubust solution would be:

    SELECT  DATEADD(DAY, CASE (DATEPART(WEEKDAY, GETDATE()) + @@DATEFIRST) % 7 
                            WHEN 1 THEN -2 
                            WHEN 2 THEN -3 
                            ELSE -1 
                        END, DATEDIFF(DAY, 0, GETDATE()));
    

    This will work for all language and DATEFIRST settings.

    0 讨论(0)
  • 2020-12-14 09:59

    You can easily make this a function call, adding a second param to replace GetDate() with whatever date you wanted. It will work for any day of the week, at any date range, if you change GetDate(). It will not change the date if the day of week is the input date (GetDate())

    Declare @DayOfWeek As Integer = 2   -- Monday
    
    Select DateAdd(Day, ((DatePart(dw,GetDate()) + (7 - @DayOfWeek)) * -1) % 7, Convert(Date,GetDate()))
    
    0 讨论(0)
提交回复
热议问题