title: How to send Query result as attachment in SQL
body: <p>This is my query and I manage to make it work to send emails.</p>
  
  <p>I have 2 columns, 
  <code>FILENAME</code> is the name of file and <code>ATTACHMENTFILE</code> is the physical file stored as <code>VARBINARY(MAX)</code>.</p>
  
  <p>I want to query out the attachment file and send out as email. So far what I am able to do is query out the file name and <code>varbinary</code> which is some hexadecimal value in a text file. And <strong>NOT</strong> the actual content of the file itself</p>
  
  <pre><code>EXEC msdb.dbo.sp_send_dbmail
       @profile_name = 'Notifications',
       @recipients = 'myemail@gmail.com',
     @execute_query_database = 'SERVER_DB',
     @query = 'SELECT FILENAME, ATTACHMENTFILE FROM SERVER_DB.dbo.EMAIL_QUEUE WHERE TRXID =2',
     --@query_attachment_filename = 'attachment.txt',
     @attach_query_result_as_file = 1,
     --@exclude_query_output = 1,
     --@query_result_header = 1,
     --@append_query_error = 1,
       @body = 'The database mail configuration was completed successfully.',
     @body_format = 'TEXT',
       @subject = 'Automated Success Message'
     ;
  GO
  </code></pre>