简体   繁体   English

在SQL Server 2008中的存储过程中导出为CSV

[英]Export to CSV in stored procedure in SQL Server 2008

I have a stored procedure that creates a temp table and has tons of data. 我有一个存储过程,可以创建一个临时表并包含大量数据。 I have tried both of the following. 我已经尝试了以下两种方法。 I can do it manually with the export utility or results to file settings, but I would like to embed the code in my stored procedure so I can schedule the batch job and forget it. 我可以使用导出实用程序手动执行此操作,也可以将结果保存到文件设置中,但是我想将代码嵌入到存储过程中,这样就可以安排批处理作业而忘记了。 Also I do not want to us SSIS for many reasons. 同样,出于多种原因,我也不希望我们使用SSIS。

Popular solution I have found are : 我发现的流行解决方案是:

bcp "select * from WHSE.Customer" queryout ExcelTest.csv -t, -c -S . -d Server1 -T

SQLCMD -S . -d Server1 -Q “"select * from WHSE.Customer sp” -s “,” -o “d:\result.csv

In the BCP it get an error on BCP, if I added an EXECUTE in front I get an error: 在BCP中,它会在BCP上出现错误,如果我在前面添加了EXECUTE ,则会出现错误:

Incorrect syntax near 'queryout'. 'queryout'附近的语法不正确。

The same goes with the SQLCMD except error on SQLCMD or -S depending on if I use the Execute command. 与这同样SQLCMD除了在错误SQLCMD-S取决于如果我使用的Execute命令。

This seems like it should be simple and I have found TONS of answers, but none actually work. 这似乎应该很简单,而且我已经找到了答案的吨,但实际上没有任何作用。 It seems like it should be the most basic thing in the world, SELECT * INTO MYFILE.CSV FROM MYTABLE essentially. 似乎应该是世界上最基本的东西,基本上是SELECT * INTO MYFILE.CSV FROM MYTABLE

You are seeing "Incorrect syntax near queryout". 您看到“查询输出附近的语法不正确”。 That is a T-SQL error message. 那是一条T-SQL错误消息。 You are ,as you said, running this from within a stored procedure. 正如您所说,您是在存储过程中运行它。 Both BCP and SQLCMD are command line utilities, meaning you will have to run them from a command (DOS) prompt. BCP和SQLCMD都是命令行实用程序,这意味着您必须从命令(DOS)提示符下运行它们。

There is a way to execute directly from SQL, but you will have to use: xp_cmdshell Here is a good article on how to use it: 有一种方法可以直接从SQL执行,但是您必须使用: xp_cmdshell这是一篇有关如何使用它的好文章:

https://www.mssqltips.com/sqlservertip/1633/simple-way-to-export-sql-server-data-to-text-files/ https://www.mssqltips.com/sqlservertip/1633/simple-way-to-export-sql-server-data-to-text-files/

This was written for SQL Server 2005 but should work on 2008 as well. 这是为SQL Server 2005编写的,但也应在2008上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM