title: SQL: Looping through a column, stored the value as a variable, run SQL, then move on to the next line?
body: <p>I'm currently shifting roles at my job and trying to teach myself some SQL Skills. </p>
  
  <p>Scenario: I'm in charge of 1 database - 10 tables with 10 Primary Keys. Every month, our code team publishes updates to the tables. I am suppose to drop the tables and generate scripts to create the updated tables. </p>
  
  <p>Rather than just drop the old tables and stored procedures, I want to rename my current tables to preserve the structure/data for whatever reason.</p>
  
  <p>In my database, I have an additional table called "TableUpdateList" with 1 column "TableName" and 10 rows - each row containing the name of the updated column (Row 1 = TableName1, Row 2 = TableName2, Row 3 = TableName3)</p>
  
  <p>I would like to be able to "loop" through the TableUpdateList Table and insert each value into a set of SQL statements. </p>
  
  <p>For Example, here are the SQL statements I want to run:</p>
  
  <pre><code>--drop the previous backup table
  IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME = '*TableName1*'+'_Old') DROP TABLE TableName1_Old
  
  -- rename the current tables to _old 
  EXEC sp_rename *TableName1*, TableName1_Old;
  </code></pre>
  
  <p>I'm trying to find a way to scroll through the column of my TableUpdateList and run the above two statements filling in where I've italicized with whatever value is present in that row.</p>
  
  <p>Just taking a wild stab because I think in order to get an answer here, you have to try something so here is my pseudo-code:</p>
  
  <pre><code>Declare @TableNames as List
  
  For i in @TableNames
  
  IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME = '*i*'+'_Old') DROP TABLE TableName1_Old
  
  -- rename the current tables to _old 
  EXEC sp_rename *i*, TableName1_Old;
  </code></pre>
  
  <p>Oi, thanks in advance for any help or a point in the right direction to where I could do some further reading about the above online. </p>