Calculate a number of working days in SQL and return the date without using Loops.
I need to create a function in Microsoft SQL server management studio that will take in a date and a number of working days as a variable and then return an end date that is however many working days in the future.
I have achieved this using a loop but was wondering if there is a more efficient way of achieving this?
The function is as follows:
[dbo].[AddWorkingDays]
(
@originaldate date,
@daystoadd INT
)
RETURNS date
AS
BEGIN
-- Declare the return variable here
Declare @days INT;
Declare @counter INT;
Declare @duedate date;
SET @days = 1
SET @counter = 0
WHILE (@counter < @daystoadd)
BEGIN
set @duedate = dateadd(DAY,@days,@originaldate)
IF @duedate Not in (SELECT [date-off] from [Non-working-days-table])
BEGIN
SET @counter = @counter + 1
END
BEGIN
SET @days = @days +1
END
END
-- Return the result of the function
RETURN @duedate
END
1条答案
按热度按时间dfty9e191#
Look at the approach to the task.See this example:
nwd - non-working-day. Original date(startdt) not included in count. It doesn't matter)
CTE result
Target query result (draft) with startdt=2023-05-30 and daystoadd=13
Example
Upd1. Corrected to take into account the comment of user1191247 for dates before first non-working-day in nwd table.