title: Debugging dynamic sql + dynamic tables in MS SQL Server 2008
body: <p>I have a messy stored procedure which uses dynamic sql.</p>
  
  <p>I can debug it in runtime by adding <code>print @sql;</code> where <code>@sql;</code> is the string containing the dynamic SQL, right before I call <code>execute (@sql);</code>. </p>
  
  <p>Now, the multi-page stored procedure also creates dynamic tables and uses them in a query. I want to print those tables to the console right before I do an <code>execute</code>, so that I know exactly what the query is trying to do.</p>
  
  <p>However, the SQL Server 08 does not like that. When I try:</p>
  
  <p><code>print #temp_table;</code> and try to compile the S.P. I get this error:</p>
  
  <hr>
  
  <p><strong>The name "#temp_table" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.</strong></p>
  
  <hr>
  
  <p>Please help.</p>
  
  <p><strong><em>EDIT:</em></strong> </p>
  
  <p>I am a noob when it comes to SQL. However, the following statement: <code>select * from #tbl;</code> does not print anything to the console when it is run non-interactively; the print statement works though.</p>
  
  <p>The following statement has incorrect syntax: <code>print select * from #tbl;</code>. Is there a way for me to redirect the output of select to a file, if stdout is not an option?</p>
  
  <p>Thanks.</p>