I have to generate a table with all non-business days and their following business day.
Given is: A table storing the weekends for certain cities.
CREATE TABLE WeekHolidays
(
CitiesId int
,Cities_Name varchar(50)
,HolidayDate int
)
Another table holding public holidays:
CREATE TABLE Holidays
(
CitiesId int
,Cities_Name varchar(50)
,HolidayDate datetime
)
Currently i am generating the weekend days for the next 2047 weeks (almost 40 years) + adding the public holidays like:
SELECT Cities_Id
,Cities_Name
,DATEADD(WEEK,sptv.number,DATEADD(DAY,(((HolidayDate - 1) + 7) %7),DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0))) as HolidayDate
FROM WeekHolidays
CROSS JOIN master..spt_values sptv
WHERE sptv.type = 'P'
UNION
SELECT Cities_Id
,Cities_Name
,HolidayDate
FROM Holidays
But now i need to add for each of those dates the next business day with the logik: rolling forward to the first day which is not in this table (for each city).
Rextester to reproduce: http://rextester.com/OZTT34904
So the result should be like:
CitiesId Cities_Name HolidayDate NextBusinessDay
3 PARIS 14.07.2017 17.07.2017
3 PARIS 15.07.2017 17.07.2017
3 PARIS 16.07.2017 17.07.2017
3 PARIS 22.07.2017 24.07.2017
3 PARIS 23.07.2017 24.07.2017
3 PARIS 29.07.2017 31.07.2017
3 PARIS 30.07.2017 31.07.2017
3 PARIS 05.08.2017 07.08.2017
3 PARIS 06.08.2017 07.08.2017
3 PARIS 12.08.2017 14.08.2017
3 PARIS 13.08.2017 14.08.2017
3 PARIS 15.08.2017 16.08.2017
3 PARIS 18.08.2017 21.08.2017
3 PARIS 19.08.2017 21.08.2017
3 PARIS 20.08.2017 21.08.2017
3 PARIS 26.08.2017 28.08.2017
3 PARIS 27.08.2017 28.08.2017
In example: HolidayDate = 14.07.2017 the next BusinessDay will be 17.07.2017, as 15.07.&16.07. are contained in the HolidayDate column (saturday&sunday are holidays in Paris).
I hope its more understandable now.
Any idea how to approach this easily and fast?
Thanks in advance! Stefan