title: Get Date Difference Between Two Rows from SQL Resultset
body: <p>I tried the method below to get the date difference between two from a SQL result set. I looked up google but no luck so I created the script below to accomplish the same. Hope it helps.</p>
  
  <pre><code>--- Query to get date difference between two rows 
  
  declare @table table (olddate datetime, newdate datetime)
  create table #table (olddate datetime, newdate datetime)
  
  DECLARE db_cursor CURSOR FOR 
  
    SELECT  CONVERT(date,[utl_recycle_date] ) as RecycleDate
    FROM XYZ
    WHERE account_number = '6900' AND match_status = 'F' 
    AND [utl_recycle_date] IS NOT NULL
    AND [utl_recycle_date] &gt; '11/01/2018'
    GROUP BY DATEDIFF(DAY, CONVERT(date,[utl_recycle_date] ), CONVERT(date, GETDATE())),CONVERT(date,[utl_recycle_date] )
    ORDER BY 1
  
  DECLARE @RecycleDate datetime 
  DECLARE @NewDate datetime 
  
  OPEN db_cursor 
  
  FETCH next FROM db_cursor INTO @RecycleDate 
  
  WHILE @@FETCH_STATUS = 0 
    BEGIN 
  
        FETCH next FROM db_cursor INTO @NewDate
  
        insert INTO #table (olddate, newdate) values (cast(@RecycleDate as date), cast(@NewDate as date))
        set @RecycleDate = @NewDate
  
    END 
  
  CLOSE db_cursor 
  
  DEALLOCATE db_cursor 
  
  select 
  olddate, newdate,
  CASE 
    WHEN DATEDIFF(DAY, olddate, newdate) = 0 THEN 1 
    WHEN DATEDIFF(DAY, olddate, newdate) &gt; 0 THEN DATEDIFF(DAY, olddate, newdate)
    END AS RecyclerFrequency  
  
  FROM #table
  
  drop table #table
  </code></pre>