title: Better alternative for Cursor using While loop to iterate Sql
body: <p>Good Day,
  I am trying to fetch dates from one of my table, containing records in millions, in database and save them in a variable using Cursor. After fetching dates i am inserting records in db at that particular date. For this I am using While Loop. It turns out that While loop is really slowing down the performance, it is taking about hours to complete execution. I am including a part of a query for further clearance.</p>
  
  <pre><code>declare @tranDateCursor cursor; 
  declare @today as date; 
  begin  
  
      set @tranDateCursor = cursor
      for
          select distinct transferDate
          from transactions
          where [type] = 'customer'
  
      open @tranDateCursor
      fetch next from @tranDateCursor
      into @today
  
      while @@fetch_status = 0  
  
      begin  
  
          declare @yesterday as date
          set @yesterday = (
                 select top(1) transferDate
                 from (
                        select distinct(transferDate) AS transferDate
                        from transactions
                        where transferDate &lt; @today
                          and [type] = 'customer'
                      ) as ODC_DATES
                 order by ODC_DATES.transferDate desc
          )  
  
          insert into transactions([type],transferDate) 
          select 'customer'
                  ,@today
          from transactions xt
              right outer join x_itransaction as y
                  on y.customer_account = xt.customer_account
                      AND y.transferDate = @yesterday
                      AND xt.transferDate = @today
          where xt.transactionId is null
              and y.transferDate = @yesterday
              and y.[type] ='customer'
  
      end
  end
  </code></pre>
  
  <p>I have tried using Table Variables instead of CURSOR with WHILE loop, but it turns out that it was too taking very much time to run. My concern is that, Is there a better alternative for a while loop in this particular scenario? </p>