Get number of weekends between two dates

CREATE FUNCTION fnc_NumberOfWeekEnds(@dFrom DATETIME, @dTo   DATETIME)

RETURNS INT AS

BEGIN

   Declare @weekends int

   Set @weekends = 0

   While @dFrom <= @dTo Begin

      If ((datepart(dw, @dFrom) = 1) OR (datepart(dw, @dFrom) = 7))    

                  Set @weekends = @weekends + 1

                  Set @dFrom = DateAdd(d, 1, @dFrom)

   End

   Return (@weekends)

END

GO

Execute the the function

SELECT fnc_NumberOfWeekEnds('2/27/2013','3/10/2013')

Reference with other date parts

Ebook Download
View all
Learn
View all