Is there a command for printing to a text file in T-SQL?

  • I would like to print to a specified text file, e.g. "c:\Temp\tmp.txt", using T-SQL. However, I cannot find a suitable command to do this. Please can someone help me out?

  • What are you trying to accomplish?

    You can use openrowset to write to a text file.

    http://msdn2.microsoft.com/en-us/library/ms190312.aspx

    If you need to export data to a text file, you can use the export data wizard or BCP. To initiate the export wizard simply right-click on the database --> tasks --> export data.

    more info: bcp

    http://msdn2.microsoft.com/en-us/library/ms162802.aspx

  • I want to write debug statements and error messages to a log. I have tried writing the information to log tables, but if an error occurs in the middle of a transaction, then the rollback causes the log information to be rolled back as well.

    If there is a way round this rollback problem, then I wouldn't need to write a text log.

  • You can save your error log data in a table variable. Table variables are nonpersistent and therefore not rolled back. You can insert the table variable data into a permenant table, after the rollback.

  • If you have access to extended stored procedure xp_cmdshell, you can use it to write to the text file. So you could use: exec master..xp_cmdshell "echo your_debug_statement >> c:\temp\temp.txt". You may construct the OS command as a variable and then use it as exec master..xp_cmdshell @strCmd. Please note that since this will execute an OS command, there may be a performance impact.

  • ...or you could use:

    sp_OACreate 'Scripting.FileSystemObject'...

    sp_OAMethod ...'Write or WriteLine'...

    Create a sproc to open the output file then use a function to write lines to it...



    PeteK
    I have CDO. It's like OCD but all the letters are in alphabetical order... as they should be.

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply