如何获得“真实”的出口输出SQL Server Management Studio 中的 CSV 格式?
我有一个在 SQL Server Management Studio 中运行的查询(连接到 SQL Server 2005 数据库)。我想以 CSV 格式导出数据。不是想要的 CSV 格式,您只需在每列之间添加逗号,而是“真正的”CSV 格式,您可以在字符串两边加上引号。这样您就可以导出包含逗号或引号的数据。
我看到的所有示例都仅限于想要的格式。我不知道引用字符串的选项在哪里。
如果 SSMS 确实无法完成这项基本任务,是否有其他工具可以轻松完成此任务?我不想每次需要数据转储时都必须编写 C# 程序。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
在 SSMS 2012 中,有一个选项可以实现此目的,在“工具”->“工具”中选项->查询结果-> SQL服务器->结果到网格,称为“保存 .csv 结果时引用包含列表分隔符的字符串”。我不知道这样的选项存在了多久,但我对两件事感到困惑:
这简直令人难以置信默认行为是 CSV 导出,但无法正确导入。我注意到 Excel 也有同样的功能,我得去看看是否也有这个选项。
同时,感谢我的同事,当我抱怨 CSV 导出器完全没用时,他向我指出了这个奇怪的功能,这是我找到的关于它的最佳链接,所以我想我应该把这里的知识是为了将来的搜索者的利益。
更新
下面的屏幕截图:
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:
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:
我的正常解决方法是将其构建到查询中:
您可以将其构建到用户定义的函数中,以使其更容易一些,但是您必须为每种数据类型构建一个单独的函数。
My normal work-around is to build it into the query:
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.
遗憾的是,该选项处于令人困惑的状态,但无法完美运行。以下至少有效。
文本限定符
作为双引号您应该可以开始了!
It's sad the option is available in a confusing state, yet not perfectly operational. The following is working at least.
text qualifier
as double-quoteyou should be good to go!
这些设置的不同组合可能会导致输出结果不正确或部分数据。这是因为微软认为解决这些问题还不够重要。我只是解释将结果发送到文件时 CSV 文件会发生什么情况。
要获得良好的结果,请执行以下操作:
打开新的查询窗口(新选项卡/会话)...如果不这样做,下面的配置将丢失并设置回默认值
编写查询来处理引号内包含引号,并将所有字符串数据类型括在引号中。另请注意,不同的 DBMS 和编程语言语法接受不同的转义双引号语法(如果使用此输出作为另一个系统的输入)。有些使用
\"
。有些使用""
。XML 使用"
;。这可能是 Microsoft 选择忽略此功能的原因,因此他们不必处理参数..如果新系统的转义序列是
""
..如果新系统的转义序列是
\"
。配置:
查询选项>结果> “复制或保存结果时包括列标题”选中“
查询选项”>结果> “保存 .csv 结果时引用包含列表分隔符的字符串” - BROKEN;不要使用!
查询选项>结果>其他未选中的
查询选项>结果>正文>逗号分隔(右上角设置)
查询选项>结果>正文> “在结果集中包含列标题”选中“
查询选项”>结果>正文>其他未选中的
查询选项>结果>正文> “每列中显示的最大字符数” - 设置为最大长度,这样字符串就不会被截断。
查询>结果到文件(这是所有 3 个选项之间的切换)
执行查询 (F5)
提示输入报告的文件名
打开文件以查看结果
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
""
... If Escape Sequence of new system is
\"
.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
您对导出为 CSV 有何看法?通过 PowerShell 的 SSMS?本文介绍如何在 SSMS 中定义外部工具,将当前选定的查询发送到导出为 CSV 的 PowerShell 脚本。
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.
在阅读了答案(特别是 iacob 的答案)并在较新版本的 SSMS 中尝试了建议的选项后,我决定深入研究并编译选项的全面概述以及它们如何影响导出格式。
将查询结果导出到文件选项
(这是使用 SSMS v18.4)
=>数据导出为“CSV”,但使用分号而不是逗号作为分隔符。
=>包含分号和/或双引号的值正确括在双引号中。
=>双引号已使用 2x 双引号正确转义。
=>完全按照其说明进行操作,只需将列标题添加为第一行。
=>与 iacob 的回答相矛盾,此选项不将分隔符更改为逗号,并且不需要用双引号将分号括起来并正确转义双引号。
=>包含换行符的值正确地用双引号括起来,并保留换行符。
选择这两个选项似乎会生成最有用的 CSV 格式,尽管它使用分号而不是逗号作为分隔符。
剩下的另一个问题是 NULL 值导出为“NULL”而不是空字段。
结论:
无论选择哪种方法(导出数据任务/将结果导出到 CSV)以及选择哪些选项,似乎仍然没有单一方法可以使 SSMS 正确导出到 CSV 并提供适当的支持逗号、分号、双引号以及空值。
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)
=> 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.
=> 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.
=> 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.
自 2016 年起,当在查询选项中选择以下选项时,这是默认行为:
列以逗号分隔,包含逗号的字段用双引号括起来。
As of 2016, this is the default behaviour when the following option is selected in Query Options:
Columns are delimited by commas, and fields containing commas are double-quote encapsulated.
我认为人们在这里提供了正确的解决方案,特别是马修·沃尔顿关于更改选项的响应,但对我来说这是不可用的(可能是因为我的数据库是旧版本)
或者,如果您能够将其导出为管道或逗号分隔和您想要的只是在列周围添加引号,然后只需在 Powershell 中运行此命令即可。
input.txt文件
命令执行后的
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.
input.txt file
After the command is executed
我认为最简单的方法是打开 Excel 并从 SQL 连接导入数据,而不是使用 SSMS 导出......
我正在使用 SSMS 2016,它没有选项“保存 .csv 结果时引用包含列表分隔符的字符串”,大概是因为它不起作用
Ron
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
您可以改为导出为制表符分隔格式。
You could export to a tab-delimited format instead.
通常我使用这种功能:
在选择中我将其放在这里:
在 SMSS 2012 中,只需右键单击网格并将结果另存为,或将所有网格 (ctrl-A) 和 ctrl-V 复制到 Excel。
这是在 MS Excel 等中管理数据的最简单方法,不会出现列问题。
当然,您必须在“工具”->“保存 .csv 结果时引用包含列表分隔符的字符串”。选项->查询结果-> SQL服务器->结果到网格,并根据需要增加
检索的最大字符数
。Usually I use this kind of function:
And in select I put it here:
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 increaseMaximum Characters Retrieved
if you need it.我知道单独使用 SSMS 无法做到这一点。我知道 TOAD 有一个 CSV 选项。不确定它是否是转义格式。如果 SSIS 是一个选项,您可以转换为转义字符串的格式(真正的 CSV),但这不在 SSMS 中。
如果您必须编写 C# 程序,我会考虑查询表,然后运行查询,因为元数据将提示哪些需要转义。
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.
由于上述所有设置都没有修复我的 SSMS (SQL Server 2014) 生成的 CSV(也没有导出制表符分隔的文件),我和一位同事制作了一个 转换脚本 (Ruby),用于将 SSMS CSV 转换为可读的 CSV。
它保留原始文件的编码、分隔符和换行符,甚至在最后进行精确的字节匹配验证(它从解析的(!)输入文件创建一个 SSMS 格式的文件,并比较两个文件)。
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).
我能够使用马修·沃尔顿的答案导出我的一个结果集,但是我的另一个结果集不起作用。我正在处理 sql 数据中的 xml 数据,因此无法使用逗号分隔或制表符分隔的输出。
我通过使用利用 pandas 的基本 python 脚本解决了这个问题。 Pandas 具有数据框对象,可以干净地存储所有数据,然后您可以将该数据框导出到 Excel 工作表中。我使用此链接来帮助我 - https://appdividend.com/2020/04/27/python-pandas-how-to-convert-sql-to-dataframe/
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/
我想建议一种替代方法。我在 SO 中添加了这个问题的书签。对很多答案和评论进行了投票。但当我需要执行从 SQL Management Studio 中的查询导出 CSV 文件的平庸任务时,情况总是一团糟。
最简单的解决方案是使用另一个工具,例如免费的 Dbeaver。
没有什么神秘的。无需重新启动。它就是有效的。
额外提示:您甚至可以导出数据,而无需先进行选择。右键单击表/数据库,您将找到一个导出数据选项。
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.
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.
这里有很多很棒的解释。但对我来说,只需使用 SQL 导出数据任务向导,目标为平面文件,我只需将文本限定符设置为“。这对我来说很有效。所有其他设置都是默认设置。
这有帮助点我的方向是正确的:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/43f39e86- 67c1-4ba1-a3ee-cd2e3688936f/导出到 csv 文件时如何处理数据中的逗号?forum=sqlintegrationservices
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
SSMS
工具>>选项>>查询结果>> SQL Server>>结果到网格,设置:“保存 .csv 结果时引用包含列表分隔符的字符串”。
在此处输入图像描述
另外,如果逗号不是默认分隔符,则很重要(北欧国家等)
控制面板>>时钟、语言和区域 >>地区>>附加设置
在此处输入图像描述
这也会引用包含换行符的单元格
作为旁注,在导入由此创建的文件时到Excel有一些需要注意的地方。 CSV 文件必须通过双击打开(来源:https://superuser.com/questions/180964/how-to-open-semicolon-delimited-csv-files-in-us-version-of-excel)另外,如果 Excel 区域设置使用 ;作为分隔符,必须在 CSV 文件的第一行添加以下内容:
sep=,
更新 2023 年 4 月 19 日
这在 SSMS 2012 中有效,但不适用于较新的版本。微软已从工具 -> 中删除了“引号字符串”选项。选项->查询结果-> SQL服务器->结果到网格方法。
目前我还没有经过测试的解决方案来规避这个问题,但在以下方面找到了一些建议:
将数据从 SQL Server Express 导出到 CSV (需要引用和转义)
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)