Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get next Date excluding weekends with start date and the number of working days using SQL ?

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 427
    Comment on it

    Hi All,
    While working with SQL, I came across the requirement to get the business days only. I had the number of working days and the starting date. Now the requirement was to get the next date by excluding all the Saturday Sunday and only to count the week days. So for this, we can create a common function which will return the date of next working day. Below is the function I have used to resolve my issue, hope it will help you too.

    1. USE [dbo.TestDB]
    2. GO
    3. /****** Object: UserDefinedFunction [dbo].[add_business_days] Script Date: 5/8/2015 4:40:20 PM ******/
    4. SET ANSI_NULLS ON
    5. GO
    6. SET QUOTED_IDENTIFIER ON
    7. GO
    8. CREATE Function [dbo].[add_business_days]
    9. (
    10. @start_date date,
    11. @no_of_days numeric
    12. )
    13. RETURNS date
    14. AS
    15. BEGIN
    16. Declare @counter numeric;
    17. Declare @new_date date;
    18. Declare @day_number numeric;
    19.  
    20. set @counter = 1;
    21. set @new_date = @start_date;
    22. /* Loop to determine how many days to add */
    23. while @counter <= @no_of_days
    24. BEGIN
    25. /* Add a day */
    26. set @new_date = DATEADD(DAY, 1, @new_date);
    27. set @day_number = datepart(dw,@new_date);
    28.  
    29. /* Increment counter if day falls between Monday to Friday */
    30. if (@day_number >= 2 and @day_number <= 6)
    31. BEGIN
    32. set @counter= @counter + 1;
    33. END
    34. END
    35. RETURN @new_date;
    36. END

    Happy Coding...
    CHEERS!!!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: