title: SQL Server: joining a declared table variable with local server tables
body: <p>I have declared a table within a stored procedure i.e : </p>
  
  <pre><code>DECLARE @fooTable table ( idfoo INT)
  
  INSERT INTO @fooTable
    EXEC getBOO 
  
  SELECT * FROM @fooTable
  </code></pre>
  
  <p>I want to join this table with other tables from my local server db i.e : </p>
  
  <pre><code>SELECT *
  FROM tbl1 
  RIGHT JOIN tbl2 ON tbl1.foofield = tbl2.foofield
  RIGHT JOIN @fooTable ON tbl2.foofield = @fooTable.foofield ; 
  </code></pre>
  
  <p>I get an error:</p>
  
  <blockquote>
    <p>Must declare the scalar variable "@fooTable"</p>
  </blockquote>
  
  <p>I've searched a bit for this error, most of the posts I found stated that the table I'm trying to reach is out of scope.</p>
  
  <p>Well the declaration of <code>@fooTable</code>, as well as the JOIN query, are a part of the same stored procedure, so i can't find any scoping issues. </p>
  
  <p>What is the best practise to JOIN a variable table (@fooTable) with tables from my local server ? (tbl1, tbl2) ?</p>