How can I output records/messages to a flat file from inside a SQL Server TSQL script/stored-procedure/trigger?

Neil Pike

April 18, 1999

1 Min Read
ITPro Today logo in a gray background | ITPro Today

A. A. SQL Server doesn't have a handy SPOOL command like Oracle does,but there are a number of ways of doing what you want.

  1. Use xp_cmdshell and the ECHO command. Use the > or >> redirectionsymbols to either create or append to a file.
    xp_cmdshell "@ECHO test message >> C:file.fil"

  2. Put the information you want into a table (note this can't be an ordinarytemporary table, but it can be a global temporary table) and then bcp it out toa file via xp_cmdshell.
    xp_cmdshell "bcp .. out c:file.fil-Usa -P -c"

  3. BCP or BULK INSERT (SQL 7 only) can also be used to read in a flat fileinto a table, from where it can be processed.

  4. Write your own extended stored procedure. As this is a C program it can usestandard file access commands to achieve whatever you want.

  5. Run the select through ISQL via xp_cmdshell and use the -o parameter tooutput the results to a file. This example uses the -E parameter to avoildhard-coding a userid.
    declare @str varchar(255)
    select @str='isql -Q"select * from " -E-oc:file.fil'
    exec master..xp_cmdshell @str

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like