title: Loop query through multiple tables
body: <p>I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:</p>
  
  <pre><code>select p.productID, po.name, p.price from prices_2001  p
  join products po on p.productID = po.id
  where price &lt; 0
  </code></pre>
  
  <p>and I would like to loop through all the years from 2001 to 2020. So it should look like this:</p>
  
  <pre><code>select p.productID, po.name, p.price from prices_2001  p
  join products po on p.productID = po.id
  where price &lt; 0
  
  select p.productID, po.name, p.price from prices_2002  p
  join products po on p.productID = po.id
  where price &lt; 0
  
  select p.productID, po.name, p.price from prices_2003  p    --Looping trough all the tables until 2020
  join products po on p.productID = po.id
  where price &lt; 0
  </code></pre>
  
  <p>If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?</p>
  
  <p>Thank you!</p>