Skip to content

Instantly share code, notes, and snippets.

@jmelosegui
Created March 17, 2016 18:23
Show Gist options
  • Save jmelosegui/52d18eb600948833b7db to your computer and use it in GitHub Desktop.
Save jmelosegui/52d18eb600948833b7db to your computer and use it in GitHub Desktop.
ufnAddBusinessDays SqlServer function
CREATE FUNCTION [dbo].[ufnAddBusinessDays]
(
@Date DATE,
@n int -- Number of days to add or substract
)
RETURNS DATE
AS
BEGIN
DECLARE @d INT,@f INT,@DW INT;
Set @f = CAST(abs(1^SIGN(DATEPART(DW, @Date)-(7-@@DATEFIRST))) as bit)
Set @DW = DATEPART(DW,@Date)-(7-@@DATEFIRST)*(@f^1)+@@DATEFIRST*(@f&1) --Calculate the Day of the Week regardless the @@DATEFIRST configuration
SET @d=4-SIGN(@n)*(4-@DW);
RETURN DATEADD(D,@n+((ABS(@n)+(@d%(8+SIGN(@n)))-2)/5)*2*SIGN(@n)-@d/7,@Date);
END
@jmelosegui
Copy link
Author

Based on this SO answer.

Features

  • No loops
  • No tables,
  • No case statements
  • No DATEFIRST dependency
  • Works with negatives

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment