title: SQL: using variables in loop to create new table
body: <p>I have a problem that I don't know how to solve in SQL. Or two problems. </p>
  
  <ol>
  <li>Create a Loop that would use table1 to update variable </li>
  <li>Use the variable in the name of source temp table and the name of final out output table. </li>
  </ol>
  
  <p>Table1 has just one column</p>
  
  <pre><code>+--------+--+
  | Header |  |
  +--------+--+
  | Name1  |  |
  | Name2  |  |
  | Name3  |  |
  | Name4  |  |
  | ...    |  |
  +--------+--+
  </code></pre>
  
  <p>So I want to Loop through those rows and use them as variable @variable. Something like:</p>
  
  <pre><code>IF OBJECT_ID('table_@variable','U') IS NOT NULL
  DROP TABLE table_@variable
  
  SELECT *
  INTO table_@variable
  FROM #@variable
  </code></pre>
  
  <p>So the first itinerary of the loop would be:</p>
  
  <pre><code>IF OBJECT_ID('table_Name1','U') IS NOT NULL
  DROP TABLE table_Name1
  
  SELECT *
  INTO table_Name1
  FROM #Name1
  </code></pre>
  
  <p>The second:</p>
  
  <pre><code>IF OBJECT_ID('table_Name2','U') IS NOT NULL
  DROP TABLE table_Name2
  
  SELECT *
  INTO table_Name2
  FROM #Name2
  </code></pre>
  
  <p>And so on as long there are rows in table1</p>
  
  <p>I hope I explained it well enough. </p>
  
  <p>Thank you for your help. 
  Matt</p>
  
  <p>p.s. I am using Microsoft SQL Server Management Studio to run my queries. </p>