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.
-
1Are you looking for bcp out?Kannan Kandasamy– Kannan Kandasamy2017-08-03 12:54:47 +00:00Commented Aug 3, 2017 at 12:54
-
1Possible duplicate of I need best practice in T-SQL Export data to CSV (with header)Radu Gheorghiu– Radu Gheorghiu2017-08-03 13:06:01 +00:00Commented Aug 3, 2017 at 13:06
2 Answers
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.