title: Use of variable table name in Query
body: <p>From time to time I need to run the same SQL Server script, every time changing one or two letters in each table name to a value which is different each time I run the script.</p>
  
  <p>How can I set  once at the beginning of the script, so that I do not need to change each table name?</p>
  
  <p>Here is a simplified example of the script, which in reality contains a lot more tables:</p>
  
  <pre><code>SELECT * FROM T_Atable1 
      WHERE ref IN (SELECT ref FROM T_Atable2)
           AND customer IN (SELECT customer FROM T_Atable3)
  </code></pre>
  
  <p>Table names are of the form T_ where:</p>
  
  <ul>
  <li>"<code>T_</code>" is fixed</li>
  <li><code>&lt;id&gt;</code> is the variable part of the table name. In the above example  = "A"</li>
  <li><code>&lt;table name&gt;</code> is the fixed name of the table.  In the above example, the fixed parts are "table1", "table2", "table3"</li>
  </ul>
  
  <p>I suspect I need to use dynamic SQL but do not know how to do this.</p>
  
  <p>SQL Server could be any version 2003+, depending on the system containing the data.</p>