Add business days to date in SQL without loops

后端 未结 25 2927
无人共我
无人共我 2020-12-02 22:54

I currently have a function in my SQL database that adds a certain amount of business days to a date, e.g. if you enter a date that is a Thursday and add two days, it will r

25条回答
  •  半阙折子戏
    2020-12-02 23:19

    *I know this is an old thread but found something extremely useful a while ago, modified it and got this.

    select ((DATEADD(d,DATEDIFF(d,0,(DATEADD (d,2,@fromDate))),@numbOfDays)))*
    

    Update: I am sorry in a haste to find a piece of code (in a single statement) and to avoid using a function, I posted incorrect code here.

    Bit mentioned above can be used if the number of days you are adding is 7 or less.

    I have changed the code with required parameters for better understanding.

    Anyway, I ended up using what 'Nate Cook' has mentioned above. And used it as a single line of code. (Because I am restraining from using functions)

    Nate's code

    select(
    DATEADD(day, (@days % 5) + 
    CASE ((@@DATEFIRST + DATEPART(weekday, GETDATE()) + (@days % 5)) % 7)
    WHEN 0 THEN 2
    WHEN 1 THEN 1
    ELSE 0 END, DATEADD(week, (@days / 5), GETDATE()))
    )
    

提交回复
热议问题