92

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.

iacob
  • 20,084
  • 6
  • 92
  • 119
Peter Recore
  • 14,037
  • 4
  • 42
  • 62
  • 2
    Because it was annoying me so much, I wrote a program of my own that uses a proper CSV writer: https://github.com/deeja/SQLtoCSV/releases – Dan May 28 '15 at 12:02
  • 7
    How on Earth has this not been fixed yet... – Rei Miyasaka Nov 17 '17 at 08:02
  • Quote encapsulation is now the [default behaviour](https://stackoverflow.com/a/61457024/9067615) in SSMS as of 2016. – iacob Mar 24 '21 at 16:15

17 Answers17

135

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

LCJ
  • 22,196
  • 67
  • 260
  • 418
Matthew Walton
  • 9,809
  • 3
  • 27
  • 36
  • 4
    Exists in SSMS 2008 as well. – Lloyd Dec 09 '13 at 13:36
  • 1
    In 2012, this setting does not apply to the export wizard which can also yield a CSV. Luckily the save-results-as method takes about 20 fewer clicks anyway. – Seth Battin Jul 06 '14 at 20:25
  • 1
    @SethBattin Hi Seth, I'm using 2012 and when I use 'Save Results As' and select CSV, I get it without enclosing quotes. Can you say how you managed to get it to include quotes? – Kate Jul 14 '14 at 14:04
  • @Simon that's the subject of this answer. The process described above does work for right-clicking. It still doesn't escape the contents of strings though, it merely wraps them in quotes. So newlines and such are still a problem. – Seth Battin Jul 14 '14 at 14:52
  • 22
    [**Note**](http://stackoverflow.com/questions/2259446/#comment19644839_11330194): SSMS will qualify a field containing a delimiter or qualifier, but it won't qualify a field that contains line breaks. So in this regard SSMS produces technically invalid CSV files – KyleMit Aug 06 '14 at 16:06
  • Excellent post! I knew there have to be something. But you are right, one definitely does тещ expect this to be an option. – Sergey Romanov Oct 16 '14 at 03:58
  • 44
    For anyone else that had the same issue I had: You need to open a new query editor window for the changes to take effect. Doing `Save Results As..` on the same result set before/after changing the behaviour makes no difference to the exported CSV. – Jason Larke Jul 08 '15 at 03:09
  • 1
    I had far better results adding a 'SQL Connection' inside the Excel workbook itself. Paste in your query there and the results are pulled in perfectly. I spent hours trying to get a CSV from SQL Management Studio 2014, but the save results function seems completly broken even with this setting turned on. – simbolo Oct 01 '15 at 14:48
  • 1
    Do what Jason Larke mentions and, surprisingly, don't save it as an existing file and overwrite. Create a new one. – smoore4 Jan 21 '16 at 13:59
  • This is not working at all. I'm ready to explode. Why does MS make everything so insanely frustrating? I've got the check box selected and confirmed in both the Query options and the general options, yet, all strings are still without quotes. – Exit Feb 26 '16 at 21:26
  • @Exit (and others who can't get this to work). 1) You need to open a new query window after you set this option. 2) The "list separator" character is as defined in your system control panel regional settings. 3) Only values containing a list separator will be contained in quotes. –  Nov 17 '16 at 09:16
  • 1
    I couldn't find this option in SSMS 2016. – Lumberjack Jan 11 '17 at 13:30
  • 15
    In SSMS v17 I found that the specified option was missing, however it appears to have been merged with the other option 'Include column headers when copying or saving the results', because checking that had the desired effect for me. Opening a new query window is still required for the setting to take effect. – Russell Horwood May 12 '17 at 07:51
  • 16
    Microsoft: "Let's make CSVs the default export format for SSMS". Also Microsoft: "Let's ignore basic implementation details." – Owen Sep 07 '17 at 15:54
  • @NineTails I love how that's not even explained or documented anywhere. – Rei Miyasaka Nov 17 '17 at 08:04
  • @ReiMiyasaka Exactly why I shared. – Russell Horwood Nov 17 '17 at 10:23
  • 1
    SSMS 2014 here. Be careful with this option: the quotation marks are not handled when export to CSV. For example, if a column value contains a leading and ending quotes, these marks are not escaped and a CSV reader will strip out these marks later. – Codism Jan 10 '18 at 20:29
  • Option is no longer present in SSMS v18. I wish it was! – m1m1k Nov 09 '21 at 20:50
12

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 2
    Might not be necessary but I find it easier to just `'"' + REPLACE(CAST(column AS VARCHAR), '"', '""') + '"'`. That way I'm not worrying about undercutting a field. – Rob Nov 23 '12 at 16:01
  • 1
    Today, I use varchar(max). When I wrote this originally, I had just come from a shop that was still on only (ugh) Sql Server 2000 and only beginning to look at 2005. – Joel Coehoorn Oct 26 '16 at 17:00
  • You might also need to preserve the column type e.g. `NVARCHAR` if the original type was `NVARCHAR`. – N. M. Apr 20 '18 at 10:03
  • Good point. varchar => nvarchar is widening, won't break things, but nvarchar => varchar might lose data. The _best_ thing to do is use whatever matches the original column, but since people tend to just copy/paste example code off of stack overflow, the code in my answer is probably better for using nvarchar (and this change is now made). – Joel Coehoorn Apr 20 '18 at 13:07
  • Since Microsoft can't do something as basic as export to a csv file, this is the best solution. My files with line breaks weren't correctly exported using the most voted solution. – neves Mar 26 '20 at 22:34
  • ```REPLACE(REPLACE(tbl.Notes, CHAR(10),''), CHAR(13),'') as Notes``` – Ben McIntyre Jun 20 '23 at 01:40
10

It's sad the option is available in a confusing state, yet not perfectly operational. The following is working at least.

  1. Choose "Tasks>Export Data" from the DB context menu (does not work at Table level either)
  2. For Source, choose "Microsoft OLE DB Provider for SQL Server"
  3. For destination choose "Flat File...", and specify "Format" as delimited and text qualifier as double-quote
  4. Select Table or query (I worked with query)
  5. Finish the wizard

you should be good to go!

r.sumesh
  • 313
  • 1
  • 3
  • 13
  • 7
    You would think this would work, but no - columns containing double quotes in the data are not properly escaped. Faux-csv is all SQL Server deals in on the export wizard. – mattmc3 Apr 04 '17 at 17:10
  • I or my consumer did not have reasons to complaint where the data had comma and single quotes in the text fields. As I've already mentioned, I was working with the query option and if you are aware about dirty fields, you can always wrap them with `quotename`. Thankfully, did not run into double quotes though. And I was suggesting a native option, instead of depending on external solutions. – r.sumesh Jul 04 '17 at 12:26
  • This option is still the most practical, even though it doesn't automatically escape double quotes. It's easy enough to escape double quotes with replace(). – Brett Donald Jun 27 '18 at 23:38
8

Different combinations of these settings can bring results in the output that are incorrect or partial data. This is because Microsoft didn't think it was important enough to fix these issues. I'm only explaining what happens with CSV files when sending the results to a file.

To get good results, do the following:

Open new query window (new tab/session) ... if you do not, configuration below is lost and set back to the defaults

Write the query to handle the quote inside the quote, and also wrap all string data types in quotes. Also be aware that different DBMS and programming language grammars accept a different syntax for an escaped double quote (if using this output as input to another system). Some use \". Some use "". XML uses ". Probably a reason Microsoft chose to ignore this functionality, so they didn't have to deal with the arguments.

.. If Escape Sequence of new system is "".

SELECT '"' + REPLACE(CAST(column1 AS VARCHAR(MAX)), '"', '""') + '"' FROM table1

.. If Escape Sequence of new system is \".

SELECT '"' + REPLACE(CAST(column1 AS VARCHAR(MAX)), '"', '\"') + '"' FROM table1

Configuration:

Query Options > Results > "Include column headers when copying or saving the results" checked

Query Options > Results > "Quote strings containing list separators when saving .csv results" - BROKEN; DO NOT USE!

Query Options > Results > others unchecked

Query Options > Results > Text > comma delimited (setting on top right corner)

Query Options > Results > Text > "Include column headers in the result set" checked

Query Options > Results > Text > others unchecked

Query Options > Results > Text > "Maximum number of characters displayed in each column" - set to max length so strings don't get truncated.

Query > Results To File (this is a toggle between all 3 options)

Execute query (F5)

Prompt for file name of report

Open file to look at results

NOTE: If you need to do this on a regular basis, you're better off just developing a program that will do this for you in .NET or Java, or whatever language you are comfortable with. Otherwise you have a high probability of making a mistake. Then be extremely aware of the syntax of the system you're importing into, before you define your export out of SQL Server.

JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245
5

How do you feel about Export to CSV from SSMS via PowerShell? This post describes how to define an external tool in SSMS that sends the currently selected query to a PowerShell script which exports to a CSV.

billinkc
  • 59,250
  • 9
  • 102
  • 159
  • So far this looks like the best bang for my buck. I haven't even added it to the External tools menu in SSMS - I am just running it from the command line. – Peter Recore May 26 '11 at 15:09
3

As of 2016, this is the default behaviour when the following option is selected in Query Options:

enter image description here

Columns are delimited by commas, and fields containing commas are double-quote encapsulated.

iacob
  • 20,084
  • 6
  • 92
  • 119
3

After reading the answers (iacob's in particular) and trying out the suggested options in a newer version of SSMS, I decided to do a deep dive and compile a comprehensive overview of the options and how they affect the export format.

Export query result to file options

(This is with SSMS v18.4)

  • No options selected:
    => Data is exported as "CSV" but with semicolons instead of commas as delimiters.
    => Values containing semicolons and/or double quotes are properly enclosed in double quotes.
    => Double quotes are properly escaped with 2x double quotes.
  • "Include column headers when copying or saving the results"
    => Does exactly what it says, just adds the column headers as the first line.
    => Contradicting iacob's anwer, this option does NOT change the delimiter to a comma and is NOT required for enclosing value with semicolons in double quotes and properly escaping double quotes.
  • "Retain CR/LF on copy or save"
    => Values containing newlines are properly enclosed in double quotes and newlines are retained.

Having both options selected seems to produce the most usable CSV format, even though it's using a semicolon instead of comma as delimiter.

Another issue that remains is that NULL values are exported as "NULL" instead of an empty field.

Conclusion:

No matter which method is chosen (export data task / export result to CSV) and which options are selected, there still seems to be no single way to make SSMS properly export to CSV with proper support for commas, semicolons, double quotes as well as null values.

7he3rain
  • 31
  • 2
  • I'm using version 18.9.2 and it behaves as I described; behaviour seems to be version / locale specific. – iacob Nov 16 '21 at 12:24
2

I think people have provided correct solutions here in particular the response from Matthew Walton about changing the options but for me that was not available (possibly because my database is older version)

Alternatively if you are able to export it as a pipe or comma delimited and all you want is add quotations around your columns then just run this command in Powershell.

Import-Csv 'C:\input.txt' -Delimiter '|' |
    Export-Csv 'C:\output.csv' -Delimiter '|' -NoType

input.txt file

1|A|Test|ABC,PQR

After the command is executed

"1"|"A"|"Test"|"ABC,PQR"
grepit
  • 21,260
  • 6
  • 105
  • 81
1

Usually I use this kind of function:

CREATE FUNCTION [dbo].[toExport]
(
    @txt varchar(max)

)
RETURNS varchar(max)
AS
BEGIN
    
    return REPLACE(REPLACE(REPLACE(@txt, ';', ','), CHAR(10), ' '), CHAR(13), ' ');

END

And in select I put it here:

SELECT dbo.toExport( column_name ) AS column_name FROM ....

And in SMSS 2012 simply Right click on a grid and save results as, or copy all grid (ctrl-A) and ctrl-V to Excel.

It's easiest way to manage data in for example MS Excel without problems with columns.

Of course you must click "Quote strings containing list separators when saving .csv results" in Tools -> Options -> Query Results -> Sql Server -> Results to Grid and increase Maximum Characters Retrieved if you need it.

iacob
  • 20,084
  • 6
  • 92
  • 119
Maciej Niemir
  • 604
  • 6
  • 8
1

I think the easiest is to open excel and import the data from SQL connection rather than using SSMS export.... I'm using SSMS 2016 and it doesn't have the option "Quote strings containing list separators when saving .csv results" presumably because it doesn't work

Ron

ron
  • 11
  • 1
0

You could export to a tab-delimited format instead.

iacob
  • 20,084
  • 6
  • 92
  • 119
Brian Wirt
  • 142
  • 3
  • 9
0

As all the settings mentioned above didn't fix the CSV my SSMS (SQL Server 2014) generated (nor exporting a tab-separated file), a colleague and I made a converter script (Ruby) to convert the SSMS CSV into readable CSV.

It keeps encoding, separators and linebreaks of the original file and even does an exact-byte-match validation at the end (it creates a file in the SSMS format from the parsed (!) input file and compares both files).

iacob
  • 20,084
  • 6
  • 92
  • 119
Niklas B.
  • 229
  • 1
  • 5
0

I know of no way to do this with SSMS alone. I know TOAD has a CSV option. Not sure if it is an escaped format. If SSIS is an option, you can convert to a format that escapes strings (true CSV), but that is not in SSMS.

If you have to write a C# program, I would consider querying the table and then running the query, as the metadata will clue which need the escape.

iacob
  • 20,084
  • 6
  • 92
  • 119
Gregory A Beamer
  • 16,870
  • 3
  • 25
  • 32
0

I would like to suggest an alternative approach. I have this question bookmarked in SO. Voted in a lot of the answers and comments. But it is always a mess when I need to do the banal task of exporting a CSV file from a query in SQL Management Studio.

The easiest solution is to just to use another tool, like the free Dbeaver.

  1. Download the Dbeaver multiplatform database tool (there is a portable version, you can use if without admin rights in your machine).
  2. Run it and create a new SQL Server connection.
  3. Open a new "Sql editor" tab
  4. Click the arrow to execute your query
  5. Right click the result grid and select "export data" and select CSV
  6. Voilá! Now you have a decently formated CSV file.

No mystery. No need to restart. It just works.

Extra tip: you can even export your data without doing a select first. Right click on the table/database and you will find a export data option.

neves
  • 33,186
  • 27
  • 159
  • 192
  • DBeaver still has slight issues if you want CR/LF in the text field replaced by spaces. Although the .csv file may render OK when opened in Excel, rows appear split on CR/LF when opened in notepad++. Obviously it's retaining these special characters. If you want them replaced by spaces, use SSMS v18 with Tools > Options > Query Results > SQL Server > Results to Grid > "Include column headers when copying or saving the results" ticked. – owl7 Dec 10 '21 at 04:21
  • @owl7 this is the correct behavior of CSV files. Lines with linebreaks are enclosed in quotes and proper CSV readers can correctly parse them. The original data isn't altered and the linebreaks will be displayed in any text editor. – neves Dec 10 '21 at 15:56
0

SSMS Tools >> Options >> Query Results >> SQL Server >> Results to Grid, Setting: "Quote strings containing list separators when saving .csv results".

enter image description here

Also, important if comma not default separator (Nordic countries et al.) Control Panel >> Clock, Language, and Region >> Region >> Additional Settings enter image description here

This also quotes cells that include linebreaks

As a sidenote, when importing thus created file to Excel there are some things to note. Csv-file must be opened with a double click (source: https://superuser.com/questions/180964/how-to-open-semicolon-delimited-csv-files-in-us-version-of-excel) Also, if Excel regional settings use ; as separator the following must be added in the first line of the CSV file:

sep=,

Update 2023-Apr-19

This has worked in SSMS 2012 but not with the more recent ones. Microsoft has removed the "quote strings" option from the Tools -> Options -> Query Results -> SQL Server -> Results to Grid method.

I've got no tested solutions to circumvent this at the moment but found some propositions in: Exporting data from SQL Server Express to CSV (need quoting and escaping)

Joona
  • 1
  • 1
  • The option `Quote strings containing list separators when saving .csv results` is not available in SSMS v18.2, v18.9.1, nor v18.10. @Joona would you mind updating your answer to include your SSMS version number where this setting is available? – TaeKwonJoe Oct 21 '21 at 19:10
0

I was able to export one of my result sets with Matthew Walton's answer, however another of my results sets was not working. I'm working with xml data in my sql data, so I cannot use either comma delimited nor tab delimited outputs.

I solved this by using a basic python script that leverages pandas. Pandas has dataframe objects that will store all of your data cleanly, then you can export that dataframe into an excel sheet. I used this link to help me - https://appdividend.com/2020/04/27/python-pandas-how-to-convert-sql-to-dataframe/

import pandas as pd
import pyodbc
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
sql_query = pd.read_sql_query(
    '''SELECT TOP (1000) [column_1]
                  ,[column_2]
                  ,[column_3]
                   FROM [My_Table]
                  ''', conn)

df = pd.DataFrame(sql_query, columns=['column_1', 'column_2', 'column_3'])
df.to_excel("exported_data.xlsx", index=False)
0

Lots of great explanations on here. But for me, simply using the SQL Export Data Task wizard, with the destination as a Flat File, I just had to set the Text qualifier to ". That did the trick for me. Every other setting was the default setting.

This helped point me in the right direction:

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/43f39e86-67c1-4ba1-a3ee-cd2e3688936f/how-to-deal-with-commas-in-data-when-exporting-to-a-csv-file?forum=sqlintegrationservices

deebs
  • 1,390
  • 10
  • 23