title: Get number of weekends between two dates in SQL
body: <p>I need to get the number of weekends between dates in sql as a function. I have tried but stuck up somewhere in the logic.</p>
  
  <pre><code>CREATE FUNCTION fnc_NumberOfWeekEnds(@dFrom DATETIME, @dTo   DATETIME)
  
  RETURNS INT AS
  
  BEGIN
  
     Declare @weekends int
  
     Set @weekends = 0
  
     While @dFrom &lt;= @dTo Begin
  
        If ((datepart(dw, @dFrom) = 1))    
  
                    Set @weekends = @weekends + 1
  
                    Set @dFrom = DateAdd(d, 1, @dFrom)
  
     End
  
     Return (@weekends)
  
  END
  </code></pre>