Click here to Skip to main content
15,882,017 members
Articles / Database Development / SQL Server
Tip/Trick

Extending DATEADD Function to Skip Weekend Days

Rate me:
Please Sign up or sign in to vote.
4.57/5 (4 votes)
17 Apr 2015CPOL 32.8K   7   4
A quick method to add days to a date, skipping weekend days if the number of days added results in a Saturday/Sunday

Introduction

Sometimes, speaking about date extraction or calculation from a database, it could be required to take into account weekend days. For example, we are managing order dates, and we need to postpone them. If shipments can't be done on weekends, it could be useful to have a DATEADD-like function to postpone our date to a working day. The following code will accomplish the task.

Using the Code

Just copy and paste the following into SQL Management Studio: a new function will be created to be used in future queries.

SQL
CREATE FUNCTION DAYSADDNOWK(@addDate AS DATE, @numDays AS INT)
RETURNS DATETIME
AS
BEGIN
    SET @addDate = DATEADD(d, @numDays, @addDate)
    IF DATENAME(DW, @addDate) = 'sunday'   SET @addDate = DATEADD(d, 1, @addDate)
    IF DATENAME(DW, @addDate) = 'saturday' SET @addDate = DATEADD(d, 2, @addDate)
 
    RETURN CAST(@addDate AS DATETIME)
END
GO

The new function can be executed like usual ones:

SQL
SELECT dbo.DAYSADDNOWK(GETDATE(), 3)

where GETDATE() function can be substituted by the needed date, and the example value of "3", representing the number of days to be added, could be replaced by any value in the scope of INT.

History

  • 2015-04-17: First release for CodeProject

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Italy Italy
Working in IT since 2003 as Software Developer for Essetre Srl, a company in Northern Italy.
I was awarded in 2014, 2015 and 2016 with Microsoft MVP, for Visual Studio and Development Technologies expertise. My technology interests and main skills are in .NET Framework, Visual Basic, Visual C# and SQL Server, but i'm proficient in PHP and MySQL also.

Comments and Discussions

 
SuggestionEdit for all of situations Pin
Quchen52020-Apr-15 20:15
Quchen52020-Apr-15 20:15 
QuestionMisleading Title Pin
Les Wills20-Apr-15 14:03
Les Wills20-Apr-15 14:03 
GeneralMy vote of 4 Pin
Suvendu Shekhar Giri18-Apr-15 0:51
professionalSuvendu Shekhar Giri18-Apr-15 0:51 
GeneralRe: My vote of 4 Pin
Emiliano Musso18-Apr-15 3:56
professionalEmiliano Musso18-Apr-15 3:56 
Hi, thank you for your comment! Smile | :)
You gave me an idea to extend my script, thank you!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.