I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in. The date rule already has values but the expected date column is what is updated manually. If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month. If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth. Is it possible to write an update query where it would loop through the values and update automatically? I'm having trouble figuring out to update to the correct business day.
date rule | March expected date | April expected date | -------------------------------------------------------- | BD1 | 3/1/2017 | 4/3/2017 | | BD2 | 3/2/2017 | | | BD3 | 3/3/2017 | | | BD4 | 3/6/2017 | | | BD5 | | | | BD6 | | | | CD1 | 3/1/2017 | | | CD2 | 3/2/2017 | | | CD3 | 3/3/2017 | | | CD4 | 3/4/2017 | | | CD5 | 3/5/2017 | | | CD6 | 3/6/2017 | |
I was using the following code to calculate the first business day
SELECT DATEADD(DAY,
CASE
(DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
WHEN 6 THEN 2
WHEN 7 THEN 1
ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
)
but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday. i'm getting stumped in how to tackle this. I'm thinking a loop update query would be best
here you go. This recursive CTE will give you the BDs for the whole month:
Result:
However, in reality your query should also check for the holidays.
A calendar/tally table would do the trick, but we can use an ad-hod tally table.
Returns
IMHO , your table structure is wrong in two way, i) daterule column should be split in 2 columns like in my CTE.Then calculation will be far easier.
ii) Secondly you don't keep your column in such pivoted manner.this it will keep on increasing.So hope your handling your requirement in correct way.
Keeping your current structure in mind,
you can use this logic.. where will find the next business day skipping the weekends.