How do I output the results of a simple SQL statement to a text file??

I have this simple SELECT statement but am struggling to output it to a file using SQL Server 2005:


SELECT dbo.quoteproduct.quoteid, dbo.quoteproduct.productgroupid,
dbo.product.productname, dbo.product.description, dbo.quoteproduct.price
FROM dbo.quoteproduct, dbo.product
WHERE dbo.quoteproduct.productid = dbo.product.productid;

In other versions of SQL like Sybase I can use the command OUTPUT TO as below but this doesnt work:

OUTPUT TO 'D:\QuoterQuoteDetails.txt'                    
FORMAT ascii                     
DELIMITED BY '|'                    
QUOTE '';                    

After bing'ing it I have found that you can call an xp_cmdshell to output query results but this only seems to store data in a temporary table not a file.

Id appreciate any help on this. Many thanks Andy

more ▼

asked Nov 16, 2009 at 12:34 PM in Default

avatar image

Andy Watts
2 2 2 2

(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

You want BCP, something like:


SET @cmd = 'bcp "...Select <fieldlist> from <table>..." queryout'
+' "D:\QuoterQuoteDetails.txt" -c -T'

EXEC master..xp_cmdshell @cmd, NO_OUTPUT

Should do the trick.

more ▼

answered Nov 16, 2009 at 12:40 PM

avatar image

1.7k 2 3 6

(comments are locked)
10|1200 characters needed characters left

You can also right-click the query window: "Query Options | results | text" formatting options, then (right-click) query window and change "results to" to file.

This is a quick, one-time way redirect the output to a file.

more ▼

answered Nov 16, 2009 at 01:18 PM

avatar image

1.8k 3 5

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.



asked: Nov 16, 2009 at 12:34 PM

Seen: 1776 times

Last Updated: Nov 16, 2009 at 01:33 PM

Copyright 2018 Redgate Software. Privacy Policy