SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Piping a Query to a Text File

By Brian Knight, 2001/05/21

Total article views: 9051 | Views in the last 30 days: 190
The case where one has to send the results of a query to a text file comes up quite often. General this case take the form of a maintenance script that you run through Agent nightly and would like to see the results in the morning.

In the above example, you can create a CMDEXEC job to run the below command. This will output the results of the query inside c:\inputquery.txt to a separate file.

\mssql7\binn\osql -Usa -Ppassword -ic:\inputquery.txt -oc:\outputdir\output.txt

You can also use -E switch for trusted connection if you don't want to hard code a password into your job. From an Query Analyzer window or inside the stored procedure you can run the above statement with an extended stored procedure called XP_CMDSHELL:

master..xp_cmdshell 'osql -Usa -Pmisty -Q"select * from products" -dNorthwind -oc:\output.txt'

The -Q parameter in the above syntax runs the query then exits ISQL. You may also want to add the additional NO_OUTPUT parameter at the end of query as shown below to supress any output to the client:

master..xp_cmdshell 'osql -Usa -Pmisty -q"select * from products" -dNorthwind -oc:\output.txt', no_output

There are other methods of piping a query to a text file by using OLE Automation but they are much more complex than this method.

By Brian Knight, 2001/05/21

Total article views: 9051 | Views in the last 30 days: 190
Your response
 
 
Related tags

Advanced Querying    
T-SQL    
 
Like this? Try these...

SQL Server T-SQL in 10 Minutes

By Steve Jones | Category: Book Reviews
(not yet rated) | 2,094 reads
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com