title: SQL Server 2008 - Alternatives to While Loop
body: <p>I have an INSERT statement that operates within a WHILE loop. In each iteration of the WHILE loop, some functions are called with dates variables passed as parameters. These date variables increase by one day at each iteration of the loop.</p>
  
  <p>This is a stripped down example:</p>
  
  <pre><code>-- Start and End Date
  DECLARE 
       @StartDate DATE = '20170101'
      ,@EndDate   DATE = '20170110'
  
  -- Initialise Loop variables to Start Date
  DECLARE
       @InsertDate  DATE = @StartDate
      ,@NextDate    DATE = @StartDate  
  
  -- Loop for All Dates
  WHILE (@InsertDate &lt;&gt; @EndDate)
  BEGIN
       -- Gather Data to Insert
       INSERT INTO tblCombinedData
       SELECT 
           a.SomeString
          ,b.SomeNumber
          ,dbo.fnDoSomeStuff(a.AKey,@InsertDate,@NextDate)
          ,dbo.fnDoSomeMoreStuff(b.AKey,@InsertDate,@NextDate)
      FROM
          tblATable a 
      INNER JOIN tblAnotherTable b 
          ON a.ID = b.ID
  
      -- Move to next Set of Dates
      SET @InsertDate = DATEADD(DAY,1,@InsertDate)
      SET @NextDate   = DATEADD(DAY,1,@InsertDate)
  END
  </code></pre>
  
  <p>Is There a more efficient way of achieving this combined insert? (possibly via a CTE?) Thanks.</p>
  
  <p>Note: (SQL Server 2008 R2)</p>