使用 SQLCMD.EXE 导出 CSV 数据

发布于 2024-09-26 20:25:10 字数 412 浏览 1 评论 0原文

我正在尝试将数据从 SQL Server 导出为 CSV 格式。我有一个定期运行的蝙蝠任务来执行此操作。命令是:

SQLCMD.EXE -d [db details] -i c:\export.sql -o c:\export.csv -s"," -W 

SQL 文件只是视图中的 SELECT * 。

除了某些行在数据中包含逗号之外,此方法有效,因此需要用引号引起来的值。我可以将列分隔符更改为“','”,但随后我还需要 SQL Server 转义数据中的单引号。

不幸的是,将分隔符更改为另一个字符不太可能在 100% 的情况下解决问题,因为其中一个字段包含来自另一个应用程序的序列化数据,而另一个应用程序包含各种奇怪而奇妙的字符。

有什么方法可以让我获得标准的、引用的 CSV 数据吗?

I'm trying to export data from SQL Server into CSV format. I have a bat task to do this that's run at regular intervals. Command is:

SQLCMD.EXE -d [db details] -i c:\export.sql -o c:\export.csv -s"," -W 

The SQL file is just a SELECT * from a view.

This works except that some of the rows have commas in the data, so the values need to be quoted. I could change the column separator to be "','", but then I'd need SQL Server to escape single quotes in the data as well.

Unfortunately changing the separator to another character is unlikely to solve the problem in 100% of cases as one of the fields contains serialized data from another application which contains all sorts of weird and wonderful characters.

Is there any way for me to get standard, quoted CSV data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℉服软 2024-10-03 20:25:10

您应该能够修改 SELECT 语句以使用 QUOTENAME 函数。当然,您必须单独列出所有列,而不是使用 SELECT *

注意:在屏幕上可能很难阅读,但 QUOTENAME 的第二个参数是:

{单引号} {双引号} {单引号}

SELECT QUOTENAME(Column1, '"'), QUOTENAME(Column2, '"')
    FROM YourView

You should be able to modify your SELECT statement to use the QUOTENAME function. You would, of course, have to list all the columns individually rather than using SELECT *.

Note: It may be hard to read on the screen, but the second parameter for QUOTENAME is:

{single quote} {double quote} {single quote}

SELECT QUOTENAME(Column1, '"'), QUOTENAME(Column2, '"')
    FROM YourView
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文