Created
March 17, 2016 18:23
-
-
Save jmelosegui/52d18eb600948833b7db to your computer and use it in GitHub Desktop.
ufnAddBusinessDays SqlServer function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on this SO answer.
Features