title: Loop through column names in SQL Server
body: <p>I have a table called WorkDetails that has the following column names:
  <em>ChargeCode, ,EndShiftDate, A1, B1, C1, A2, B2, C2,......,A10, B10, C10</em>
  All the columns A,B, and C have numeric values representing the hours spent on a task for a particular date.
  I am able to write an insert statement like this one:</p>
  
  <p><code>insert into myTable
  (chargeCode, EndShiftCode, [hours])
  select chargeCode, DATEADD(dd, -10, EndShiftCode), sum(A1)
  FROM   WorkDetails
  Where ChargeCode in (1,2,5)
  group by chargeCode, EndShiftCode, A1</code></p>
  
  <p><code>insert into myTable
  (chargeCode, EndShiftCode, [hours])
  select chargeCode, DATEADD(dd, -9, EndShiftCode), sum(A2)
  FROM   WorkDetails
  Where ChargeCode in (1,2,5)
  group by chargeCode, EndShiftCode, A2</code></p>
  
  <p>The problem is that I have to write it 30 times to change the column name from A1 to A10, B1 to B10, C1 to C10.</p>
  
  <p>Is there a better way to write the insert statements where I can specify the column name to be "Where ColName like 'A%'" by looping through all the columns that start with A, then B, and C?</p>
  
  <p>Thanks!</p>