Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any straightforward way to output text files (or CSV) from SQL Server?

Tags:

sql

sql-server

I've done a fair amount of tinkering and searching and the best option seems to be either:

  1. sending output to text and copy/pasting into a text file or Excel OR

  2. outputting to a somewhat unorthodox .rpt file, which I'm not sure what you'd do with--opening it in Excel doesn't preserve formatting present in the original output.

For what seems like a pretty common task, I'm surprised there isn't a simpler way to do this.

Can anyone suggest an easier way to go about this than the two methods I outlined?

Oh, and for what it's worth, I'm working on SQL Server 2008.

like image 786
Chris Avatar asked Dec 02 '11 17:12

Chris


4 Answers

How about the BCP utility? http://msdn.microsoft.com/en-us/library/ms189569.aspx

like image 99
PowerUser Avatar answered Nov 13 '22 17:11

PowerUser


Even through the SSMS GUI, it's still a relatively PITA process:

Plan A:

  1. Tools, Options, Query Results, Results to Text <= Change output format from "fixed columns" to "delimit by tabs"

  2. At that point, you can "Save results to File", and specify a .csv file

Plan B: fire up your favorite scripting language (like vb.net, for example) and just write a program that does the SQL query and writes the .csv. 10 lines, tops :)

Plan C: Yet another approach is to use some external program to do the query and convert the results for you. SQL Server comes with "BCP". You can easily write a .bat file to invoke it:

http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/

'Hope that helps

like image 40
paulsm4 Avatar answered Nov 13 '22 15:11

paulsm4


Are you using SQL Server Management Studio? If so, when you open a new query window, you can select to send output to a file. Query Menu -> Results To -> Results to File.

like image 24
DCNYAM Avatar answered Nov 13 '22 17:11

DCNYAM


Chris, this is actually super-easy.

If your query results get displayed in the grid (as is the default), just right-click on the grid and choose Save Results As....

Save a single result-set to a file

like image 29
Evgeniy Berezovsky Avatar answered Nov 13 '22 16:11

Evgeniy Berezovsky