简体   繁体   中英

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.

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:

Incorrect syntax near 'queryout'.

The same goes with the SQLCMD except error on SQLCMD or -S depending on if I use the Execute command.

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.

You are seeing "Incorrect syntax near queryout". That is a T-SQL error message. 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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