Published on

March 17, 2023

Using NETWORKDAYS Function in SQL Server

Calculating working days in SQL Server can be a common requirement in many business scenarios. In the past, achieving this involved complex data modeling and calculations. However, with the introduction of the NETWORKDAYS function in SQL Server, this task has become much simpler and more efficient.

What is the NETWORKDAYS Function?

The NETWORKDAYS function in SQL Server returns the number of whole workdays between two dates, excluding weekends and optional holidays. It takes two mandatory parameters (start_date and end_date) and two optional parameters (weekend and holidays).

How to Use the NETWORKDAYS Function

To calculate working days using the NETWORKDAYS function, follow these steps:

  1. Create a separate table for holidays, if not already defined. This table should contain a single column of dates representing the holidays.
  2. Determine which days are considered weekend days. This can vary depending on your organization or business rules.
  3. Create a column or a measure to calculate the total working days between the start and end dates, excluding weekends and holidays.

Example:

Let’s consider a scenario where we have a table with start_date and end_date columns, and we want to calculate the total working days between these dates.

CREATE TABLE Workdays (
  start_date DATE,
  end_date DATE
);

INSERT INTO Workdays (start_date, end_date)
VALUES ('2022-08-01', '2022-08-31');

To calculate the total working days, excluding weekends and holidays, we can use the following query:

SELECT start_date, end_date, NETWORKDAYS(start_date, end_date, 1, 'HolidayTable') AS total_working_days
FROM Workdays;

The result will be:

start_dateend_datetotal_working_days
2022-08-012022-08-3122

By specifying the weekend parameter as 1 (Saturday and Sunday) and providing the holiday table, the NETWORKDAYS function calculates the total working days between the start and end dates.

Using the NETWORKDAYS function in SQL Server simplifies the process of calculating working days and improves the efficiency of your queries. It eliminates the need for complex data modeling and calculations, making it easier to implement and maintain.

So, the next time you need to calculate working days in SQL Server, consider using the NETWORKDAYS function for a more streamlined approach.

Article Last Updated: 2022-08-16

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.