4

in SqlServer management studio, you can export query results to a csv file by right click -> "Save Results as" -> csv. However, the csv file does not contain column headers and does not escape any commas in the data itself, which often leads to a malformed file.

How can I export query results with headers and commas properly handled?

Gabe Moothart
  • 153
  • 1
  • 1
  • 5
  • See also: [How to get export output in “real” CSV format in SQL Server Managment Studio? (SO)](http://stackoverflow.com/q/6115054/282105) – SandRock Sep 15 '16 at 09:56

2 Answers2

5

See Options > Query Results > SQL Server > Results to Text

Check "include column headers". My text results are being enclosed in doublequotes so that should take care of the comma issue. Take a look at the "Results to grid" tab as well - I see a "Quote strings containing list separators when saving .csv results"

If not through SSMS then you can also use the sqlcmd command line utility which includes more options than the powershell equivalent.

Sam
  • 1,990
  • 1
  • 14
  • 21
1

Not through Management Studio, but you can do this with the powershell integration in 2008. right-click in the object explorer and click "Start Powershell", then:

Invoke-Sqlcmd -ServerInstance '.\sqlexpress' -Database 'temp' -Query "select * from t" | Export-Csv file.csv -notype
Gabe Moothart
  • 153
  • 1
  • 1
  • 5
  • This method works a little better than the accepted answer, though it requires use of PowerShell. Using this from now on to export CSV. – Giscard Biamby Jan 05 '13 at 20:57