Nice! I needed a slightly more flexible version so I refactored to include parameters for defining which days are business days, and to exclude the first or last day. Instead of a loop I used a recursive CTE to get the dates so it could be joined for extra flexibility. You can easily modify this to be a procedure that returns all of the business days as a result set of dates. Just change the select list at the end to be * instead of @NumberOfBusinessDays = COUNT(*) EDIT: Wrote this on SQL Server, not sure if there is anything T-Sql specific here that might not work on MySQL.
CREATEORALTERFUNCTIONdbo.CalculateBusinessDays(@StartDatedate,@EndDatedate,@BusinessDayOfWeekStartint=2,@BusinessDayOfWeekEndint=6,@ExcludeStartDatebit=1,@ExcludeEndDatebit=0)RETURNSintASBEGINDECLARE@NumberOfBusinessDaysint=0;IF(/* Date validation */@StartDateISNULLOR@EndDateISNULLOR@StartDate>@EndDate)BEGIN/* Error - Let caller know by returning NULL */RETURNNULLENDSELECT/* Exclued Start/End date? */@StartDate=DATEADD(DAY,1*@ExcludeStartDate,@StartDate),@EndDate=DATEADD(DAY,-1*@ExcludeEndDate,@EndDate);WITHAllDatesAS(/* Generate a list of all dates between your @StartDate and @EndDate using a recursive CTE */SELECTMyDate=@StartDateUNIONALLSELECTMyDate=CAST(DATEADD(DAY,1,MyDate)ASdate)FROMAllDatesWHEREMyDate<@EndDate),BusinessDaysAS(/* build a list of business days using recursive CTE */SELECTDayOfWeek=@BusinessDayOfWeekStartUNIONALLSELECTDayOfWeek=DayOfWeek+1FROMBusinessDaysWHEREDayOfWeek<@BusinessDayOfWeekEnd)SELECT@NumberOfBusinessDays=COUNT(*)-- Replace this with * to get a list of all of the dates that are business days insteadFROMAllDatesASadWHEREDATEPART(WEEKDAY,ad.MyDate)IN(SELECTDayOfWeekFROMBusinessDays)RETURN@NumberOfBusinessDaysEND-- IF your business has non-consecutive business days like Mon-Tue and Thur-Sat then you can replace the BusinessDays CTE with this one--BusinessDays AS (/* build a list of business days using hard coded values using a table value contructor */-- SELECT-- *-- FROM ( VALUES (2), (3), (5), (6), (7)) AS BusinessDays (DayOfWeek)--),----TEST CODE--Select [dbo].[CalculateBussinessDays] ('02/18/2021', '03/06/2021')
Nice! I needed a slightly more flexible version so I refactored to include parameters for defining which days are business days, and to exclude the first or last day. Instead of a loop I used a recursive CTE to get the dates so it could be joined for extra flexibility. You can easily modify this to be a procedure that returns all of the business days as a result set of dates. Just change the select list at the end to be
*
instead of@NumberOfBusinessDays = COUNT(*)
EDIT: Wrote this on SQL Server, not sure if there is anything T-Sql specific here that might not work on MySQL.
Awesome!!
Thanks lot for taking your time to do this.