title: Local variables in sp_send_dbmail?
body: <p>I'm working on an SQL stored procedure that is supposed to send an attachment with the results of a query.</p>
  
  <p>I am using <code>sp_send_dbmail</code> to send the email.</p>
  
  <p>Within the query I'd like to send, I join the to a table variable. When I executed the stored procedure, I got an error message which said that the variable didn't exist.</p>
  
  <p>My code: </p>
  
  <pre><code> DECLARE @t TABLE (
      id INT IDENTITY(1,1),
      some fields
   )
  
  DECLARE @query VARCHAR(MAX)
  SET @query =  'SELECT 
      some values
   FROM @t t
    INNER JOIN dbo.Table d ON t.field = d.field
  EXEC msdb.dbo.sp_send_dbmail @recipients=@recipients_list,
          @subject = @subject,
          @query = @query,
          @attach_query_result_as_file = 1, 
          @query_result_width = 4000, 
          @query_attachment_filename = 'Details.txt'
  </code></pre>
  
  <p>Is there any way for me to refer to the local variable within this stored procedure? If not, why not?</p>
  
  <p>TIA!</p>
  
  <p>(I am using SQL Server 2005)</p>