I can quite easily dump data into a text file such as:
sqlcmd -S myServer -d myDB -E -Q "select col1, col2, col3 from SomeTable"
-o "MyData.txt"
However, I have looked at the help files for SQLCMD
but have not seen an option specifically for CSV.
Is there a way to dump data from a table into a CSV text file using SQLCMD
?
Since following 2 reasons, you should run my solution in CMD:
Login username & password is sometimes necessary to query a remote SQL Server instance
You can do it in a hackish way. Careful using the
sqlcmd
hack. If the data has double quotes or commas you will run into trouble.You can use a simple script to do it properly:
Source: Writing SQL output to CSV with VBScript.
Alternate option with BCP:
Is this not
bcp
was meant for?Run this from your command line to check the syntax.
For example:
Please, note that
bcp
can not output column headers.See: bcp Utility docs page.
Example from the above page:
You can run something like this:
-h-1
removes column name headers from the result-s","
sets the column seperator to ,-w 700
sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)This answer builds on the solution from @iain-elder, which works well except for the large database case (as pointed out in his solution). The entire table needs to fit in your system's memory, and for me this was not an option. I suspect the best solution would use the System.Data.SqlClient.SqlDataReader and a custom CSV serializer (see here for an example) or another language with an MS SQL driver and CSV serialization. In the spirit of the original question which was probably looking for a no dependency solution, the PowerShell code below worked for me. It is very slow and inefficient especially in instantiating the $data array and calling Export-Csv in append mode for every $chunk_size lines.