Reputation: 1242
I want to transfer SQL query results to a new csv file. This is because I have placed my SQL query inside a loop which will generate export query results to csv file each time. I'm using MS SQL Server 2012. I don't want to take GUI option.
Upvotes: 0
Views: 448
Reputation: 176
There are multiple ways to attain this. Either you can export the resultset using BCP
or using IMPORT/ EXPORT
or using CTRL+SHIFT+S (this will change the resultset to SAVE AS
. Hope this may help.
Upvotes: 0
Reputation: 3993
Sql Server is not really designed to import and export files. You can use bulk copy program but I dont think it works in tsql code (looping). You can use openrowset but you need to set a special flag that opens up your surface area of attack which some do not want to do.
The answer is SSIS (or a tool like Talend). It comes with Sql and is designed by MS as the go to tool for import and export from Sql. If you were to right click on the data base, choose tasks and then export the wizard eventually creates and executes an SSIS package.
I recommend you reconsider a GUI option.
ps - Another answer was to use save results as. I have heard of problems using this method including problems with delimiters or text qualified fields.
Upvotes: 1