Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP
How to Calculate the Count of Working Days Between Two Dates using T-SQL User Defined Function
In Transact-SQL it's a common problem to calculate the number of working days between two dates.
SQL developers use user defined functions to calculate count of working days for reusability of t-sql code.
In this t-sql tutorial, I'll start with sql code samples that will help you calculate number of working days between two days excluding holidays.
To make it simple for the first T-SQL example, we'll consider only yearly holidays of the working staff.
First start with creating sql table EmployeeHolidayPlanning which stores employees' holiday start and end dates.
The first SQL script will also generate sample data to populate SQL database table EmployeeHolidayPlanning.
Here is how sample sql data is seen on holiday planning table where holiday periods of employees are stored
And here is the sample SQL Server user-defined function which can be used to calculate working days between two dates.
Here the employee id is passed to the sql function as a parameter.
Other sql parameters are boundries of the time period; begin date and end date parameters.
Please note that the following dbo.GetWorkingDaysCountForEmployee sample SQL function only considers the holiday table given above.