Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get export output in "real" CSV format in SQL Server Management Studio?

I have a query that I am running in SQL Server Management Studio (connecting to a SQL Server 2005 database). I want to export the data in CSV format. Not wannabe CSV format, where you just stick a comma between each column, but "real" CSV format, where you put quotes around your strings. This way you can export data that has commas or quotes in it.

All the examples I see limit themselves to the wannabe format. I can't figure out where the option to quote strings is.

If SSMS is truly incapable of this basic feat, are there other tools that will do it easily? I don't want to have to write a C# program every time I need a data dump.

like image 617
Peter Recore Avatar asked May 24 '11 18:05

Peter Recore


People also ask

How do I change the output format in SQL Server?

I presume you are trying to change the result view in SQL Server Management Studio. If this the case what you need is 'Result to Grid' option. You can also use Ctrl + D to change the view to grid and 'Ctrl + T' to change it back to text.


2 Answers

In SSMS 2012 there's an option for this, in Tools -> Options -> Query Results -> SQL Server -> Results to Grid, it's called "Quote strings containing list separators when saving .csv results". I don't know how long such an option has existed for, but I'm baffled by two things:

  1. How come it's not turned on by default
  2. How come it's an option and not an intrinsic part of the CSV exporting code

It just defies belief that the default behaviour is to have CSV export that's impossible to import properly. I've noticed Excel does the same, I'll have to go see if that's got an option too.

In the mean time, thanks to my colleague who pointed me to this bizarre bit of functionality when I was ranting about how the CSV exporter was completely useless, and this was the best link I'd found about it so I thought I'd put the knowledge here for the benefit of future searchers.

UPDATE

A screenshot below:enter image description here

like image 151
Matthew Walton Avatar answered Sep 29 '22 11:09

Matthew Walton


My normal work-around is to build it into the query:

SELECT '"' + REPLACE(CAST(column AS NVARCHAR(4000)), '"', '""') + '"' AS Header, ... FROM ... 

You can build that into a user-defined function, to make it a little easier, but you have to build a separate function for each data type.

like image 45
Joel Coehoorn Avatar answered Sep 29 '22 12:09

Joel Coehoorn