title: How do you email a query result as a csv using sp_send_dbmail stored procedure with SQL?
body: <p>I would like to send an email containing the results of a query as a csv attachment.</p>
  
  <p>So far I have this;</p>
  
  <pre><code>EXEC msdb.dbo.sp_send_dbmail
      @recipients='me@myself.com',
      @subject='CSV Extract', 
      @profile_name = 'Valid profile',
      @body='See attachment',
      @query ='SELECT TOP 10 c.* FROM MyDb.dbo.Customers c',
      @attach_query_result_as_file = 1,
      @query_attachment_filename = 'CSV_Extract.csv',
      @query_result_separator = ','
  </code></pre>
  
  <p>I receive the email with a csv attachment but when opened in Excel the results are horribly formatted (e.g. all values are in a single column with seemingly random indentation)</p>
  
  <p>What should I be doing to get a correctly formatted result with correct column headers etc?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have added the following parameters to the query;</p>
  
  <pre><code>@query_result_width = 32767,
  @query_result_no_padding = 1
  </code></pre>
  
  <p>This improved things a lot however I am still getting each record in a single column when opened inside Excel. How can I place each value within a record into it's own column?</p>
  
  <p>This is what I currently get;</p>
  
  <p><a href="https://i.stack.imgur.com/wKauv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKauv.png" alt="enter image description here"></a></p>
  
  <p>This is what I'm after;</p>
  
  <p><a href="https://i.stack.imgur.com/SZHBS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SZHBS.png" alt="enter image description here"></a></p>