title: SQL - Find working hours between 2 dates excluding weekends
body: <p>I'm working on a code to get net working days excluding weekends (saturday and sunday). I need this data in days. I've written following 2 functions for it </p>
  
  <p>The first function returns the start time of the date</p>
  
  <pre><code>ALTER FUNCTION day_start
     (@dd as datetime)
     returns datetime
     begin
       return cast(floor(cast(@dd as float)) as datetime)
     end
  </code></pre>
  
  <p>The second one does the actual work</p>
  
  <pre><code>alter function networkingdays_hours (@startdate as datetime, @enddate as datetime)
  returns float
  begin
  return
  (
  
  SELECT
      cast(
      (DATEDIFF(dd,@StartDate, @EndDate))
      -(DATEDIFF(wk,@StartDate, @EndDate)*2)
      -(CASE WHEN DATENAME(dw, @StartDate) ='Sunday'
        THEN 1
              ELSE 0
          END)
      -(CASE WHEN DATENAME(dw, @EndDate) ='Saturday'
        THEN 1
              ELSE 0
          END)        
      +(@EndDate - dbo.day_start(@EndDate))
          -(@startdate - dbo.day_start(@startdate))
           as float))
      END
  </code></pre>
  
  <p>Example
  start time - 8/31/2012  9:22:00 AM, End Time - 9/1/2012  7:14:00 AM, Expected result - 0.911111111, Code output - (-0.08888888)</p>
  
  <p>Please help.</p>