We already have a function in SQL that calculates nth working date excluding weekends and holidays, when you pass Startdate, Enddate and Workday(nth).. it gives you nth working day...
Working SQL Function:
FUNCTION [dbo].[getNthWorkingDate]
(
@StartDate as datetime,
@EndDate as datetime,
@WorkDay as int
)
RETURNS datetime
AS
BEGIN
-- Declare the return variable here
DECLARE @WorkDate as datetime, @LeaveYear as smallint,@iCount as int
set @LeaveYear = datepart(year, @StartDate)
set @iCount = 1
WHILE (@StartDate < @EndDate)
BEGIN
IF (DATENAME(WEEKDAY,@StartDate ) = 'SUNDAY') OR (DATENAME(WEEKDAY,@StartDate ) = 'SATURDAY')
-- Just to keep the if statement with out code
set @iCount = @iCount;
ELSE IF EXISTS (SELECT * FROM HOLIDAYS WHERE CAST (HOLIDAY + ' ' + CAST(@LeaveYear AS VARCHAR) AS DATETIME) = @StartDate)
-- Just to keep the if statement with out code
set @iCount = @iCount;
ELSE
begin
set @WorkDate = @StartDate
if @iCount = @WorkDay
BREAK;
else
set @iCount = @iCount + 1;
end
set @StartDate = dateadd(day, 1, @StartDate );
END
-- Return the result of the function
RETURN @WorkDate
END
I am Trying to recreate this function in ORACLE(new to oracle), i have made a few changes but couldn't get it working, i think i am missing something in the looping, any help would be appreciated... Thanks in Advance..
ORACLE Function:
create or replace FUNCTION GETNTHWORKINGDATE (pStartDate DATE,
pEndDate DATE,
pWorkDay NUMBER)
RETURN DATE
AS
vStartDate DATE;
vWorkDate DATE ;
vCount NUMBER;
vHoliday DATE;
BEGIN
vCount := 1;
BEGIN
SELECT HOLIDAY_DATE INTO vHoliday FROM HOLIDAY WHERE (to_char(HOLIDAY_DATE, 'MM DD') = to_char(pStartDate, 'MM DD'));
EXCEPTION
WHEN NO_DATA_FOUND THEN
vHoliday := NULL;
END;
vStartDate := pStartDate;
BEGIN
WHILE (vStartDate < pEndDate)
LOOP
IF (to_char(vStartDate, 'DAY') = 'SUNDAY' ) OR (to_char(vStartDate, 'DAY') = 'SATURDAY') THEN
vCount := vCount;
ELSIF (to_char(vHoliday, 'MM DD') = to_char(vStartDate, 'MM DD')) THEN
vCount := vCount;
ELSE
vWorkDate := vStartDate;
IF vCount = pWorkDay THEN
EXIT;
ELSE
vCount := vCount + 1;
END IF;
END IF;
vStartDate := vStartDate + 1;
END LOOP;
END;
RETURN vWorkDate;
END GETNTHWORKINGDATE;
holiday
table and whatever sample data is needed there would also allow others to run your code. – Justin Cave Jul 21 '16 at 18:09