title: table valued function getting working days excluding weekend and holidays
body: <p>actually the function does not work properly after many tests</p>
  <p>for example I've tried<code>Select * from [dbo].[fn_GetLeaveDays] ('2020-09-24',1,'2020-09-25',1,1,1)</code>
  and it should returns only 1 as friday is weekend but it returns 2</p>
  <p>could you please assist to find whats wrong in the function</p>
  <pre><code>ALTER FUNCTION [dbo].[fn_GetLeaveDays] (@DateFrom datetime2,
                                      @CalendarFunction int,
                                      @DateTo AS datetime2,
                                      @AdjustMode bit,
                                      @AdjustWeekEnds bit,
                                      @AdjustHolidays bit)
  RETURNS @tbl table (totaldays int)
  AS
  BEGIN
  
  IF @DateFrom &gt; @DateTo
  BEGIN
      DECLARE @T datetime2 = @DateTo,
              @F datetime2 = @DateFrom;
      SELECT @DateFrom = @T,
             @DateTo = @F;
  END;
  
  DECLARE @Count AS int = 0,
          @Date AS datetime2 = @DateFrom;
  
  WHILE @Date &lt; @DateTo
  BEGIN
      IF ((DATEPART(WEEKDAY, @Date) IN (6)
       AND @AdjustWeekEnds = 1)
       OR EXISTS (SELECT *
                  FROM [C3DCalendar].[dbo].[PRIMAVERA_CALENDAR_HOLIDAYS]
                  WHERE holiday_date = @Date
                    AND calendar_key = @CalendarFunction
                    AND @AdjustHolidays = 1))
      BEGIN
          SELECT @Count = @Count + 1;
      END;
  
      SELECT @Date = DATEADD(DAY, 1, @Date);
  END;
  INSERT INTO @tbl
  SELECT (DATEDIFF(DAY, @DateFrom, @DateTo) - (@Count)) + @AdjustMode;
  RETURN;
  END;
  </code></pre>