Fix Code to Accept Negative Input for AddBusinessDays to date?

Hi Experts,

Can anyone tweak this code, below, to work with a negative date input to subtract business days from a given date?

Thanks,
Steve

ALTER function [dbo].[DateAddWorkDay]
(@days int,@FromDate Date)
returns Date
as
begin
declare @result date
set @result = (
select b
from
(
    SELECT
    b,
       (DATEDIFF(dd, a, b))
      -(DATEDIFF(wk, a, b) * 2)
      -(CASE WHEN DATENAME(dw, a) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, b) = 'Saturday' THEN 1 ELSE 0 END)
      -COUNT(o.Holiday) 
      as workday
    from
    (
    select 
    @FromDate as a,
    dateadd(DAY,num +@days,@FromDate) as b
    from (select row_number() over (order by (select NULL)) as num
          from Information_Schema.columns
         ) t
    where num <= 100 
    ) dt
    left join Holiday o on o.Holiday between a and b and DATENAME(dw, o.Holiday) not in('Saturday','Sunday') 
    where DATENAME(dw, b) not in('Saturday','Sunday')
          and b not in (select Holiday from Holiday where Holiday between a and b) 

    group by a,b
) du
where workday =@days 


)
return @result 
end

Open in new window

tablaFreakAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongSoftware Team Lead, ex-Business Systems Analyst , ex-Senior Application EngineerCommented:
what's the issue for your function posted?

you already have this:

dateadd(DAY,num +@days,@FromDate) as b

Open in new window


it should worked if @days is negative too
Raja Jegan RSQL Server DBA & Architect, EE Solution GuideCommented:
For negative @Days input, if I interpret your function correctly, you might need to change the code in 2 places:
1. Go back to the dates instead of checking forward
dateadd(DAY,-num +@days,@FromDate)

Open in new window

to
dateadd(DAY,case when num > 0 then num +@days else -num+@days end,@FromDate)

Open in new window


2. and the below WHERE condition in 2 places
where condition from
o.Holiday between a and b 

Open in new window

to
((@days > 0 AND o.Holiday BETWEEN a and b) OR (@days < 0 and o.Holiday between b and a))

Open in new window

to get the records fetched out..
If possible, kindly provide the table structure of holidays table so that I can check it out once whether this will work fine or not..
tablaFreakAuthor Commented:
Thanks guys for the input. I tried your suggestion, Raja, and I'm getting a null output in both + and - days cases.

Here's the Holiday table, below, with the code with your suggested edits.

ALTER function [dbo].[DateAddWorkDay]
(@days int,@FromDate Date)
returns Date
as
begin
declare @result date
set @result = (
select b
from
(
    SELECT
    b,
       (DATEDIFF(dd, a, b))
      -(DATEDIFF(wk, a, b) * 2)
      -(CASE WHEN DATENAME(dw, a) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, b) = 'Saturday' THEN 1 ELSE 0 END)
      -COUNT(o.Holiday) 
      as workday
    from
    (
    select 
    @FromDate as a,
       dateadd(DAY,case when num > 0 then num +@days else -num+@days end,@FromDate) as b
    from (select row_number() over (order by (select NULL)) as num
          from Information_Schema.columns
         ) t
    where num <= 100 
    ) dt
        left join Holiday o on 
		((@days > 0 AND o.Holiday BETWEEN a and b) OR (@days < 0 and o.Holiday between b and a)) 
		AND DATENAME(dw, o.Holiday) not in('Saturday','Sunday') 
    where DATENAME(dw, b) not in('Saturday','Sunday')
          and b not in (select Holiday from Holiday where Holiday between a and b) 

    group by a,b
) du
where workday =@days 


)
return @result 
end

Open in new window



CREATE TABLE [dbo].[Holiday](
	[Holiday] [date] NULL
) ON [PRIMARY]

GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-01-01' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-01-01' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-09-03' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-11-22' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-11-23' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-12-25' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-12-26' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-12-27' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-12-28' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2018-12-31' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-01-01' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-05-27' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-07-04' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-09-02' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-11-28' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-11-29' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-12-25' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-12-26' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-12-27' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-12-30' AS Date))
GO
INSERT [dbo].[Holiday] ([Holiday]) VALUES (CAST(N'2019-12-31' AS Date))
GO

Open in new window

Powerful Yet Easy-to-Use Network Monitoring

Identify excessive bandwidth utilization or unexpected application traffic with SolarWinds Bandwidth Analyzer Pack.

Raja Jegan RSQL Server DBA & Architect, EE Solution GuideCommented:
Here you go, rewritten your function to handle the negative case as well..
CREATE function [dbo].[DateAddWorkDay]
(@days int,@FromDate Date)
returns Date
AS 
begin
declare @days2 int 
set @days2 = 5*@days

declare @result date
; with cte as (
select case when @days < 0 then dateadd(dd, @days2, @FromDate) ELSE DATEADD(DD,1,@FromDate) END Start
UNION ALL 
SELECT DATEADD(DD, 1, Start)
FROM cte 
WHERE Start < case when @days < 0 then DATEADD(dd,-1,@FromDate) ELSE dateadd(dd, @days2, @FromDate) END
)
SELECT @result = Start
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY Start) anum, ROW_NUMBER() OVER (ORDER BY Start desc) dnum
FROM CTE 
WHERE NOT EXISTS (SELECT * from Holiday where holiday.holiday = cte.start)
AND DATENAME(dw,Start) NOT IN ('Saturday', 'Sunday')
) temp
WHERE ABS(@days) = case when @days < 0 then dnum else anum end
return @result 
END
-- Tested working for both cases
select dbo.DateAddWorkDay1(10, '2018-11-15')
select dbo.DateAddWorkDay1(-10, '2018-12-03')

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tablaFreakAuthor Commented:
Thanks very much,gentlemen, in particular Raja!
All the Best,
Steve
Raja Jegan RSQL Server DBA & Architect, EE Solution GuideCommented:
Welcome, Steve!!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.