x

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:

--QUOTER QUOTE DETAILS

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:

DECLARE @cmd VARCHAR(8000)

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

EXEC master..xp_cmdshell @cmd, NO_OUTPUT

Should do the trick.

more ▼

answered Nov 16, 2009 at 12:40 PM

avatar image

RickD
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

TG
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

By RSS:

Answers

Answers and Comments

SQL Server Central

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

Topics:

x2018
x426

asked: Nov 16, 2009 at 12:34 PM

Seen: 1774 times

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

Copyright 2016 Redgate Software. Privacy Policy