Piping a Query to a Text File

,

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.

Rate

4.56 (9)

Share

Share

Rate

4.56 (9)