SQL - Write to a text file

I've long used this method to write files to the file system using SQL.

This method employs the SQL  sp_OACreate and sp_OAMethod procs to do the writing. Now in SQL 2012 that method is not working for me. I switched to the XP_CommandShell method and that works fine.

So, here is the documentation of how to write a text file using XP_CommandShell

 

Related Articles

... and you 'll find more on the SQL (General) Menu

First, you need to enable XP_CommandShell, it is disabled by default

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

Then just copy in this stored procedure. There is test code included to show you how to run it.

--  Test using this:
--  EXEC DD_AppendToFile '<ExchangeRate>','D:\test\test.xml'
  
-- Drop stored procedure if it already exists
IF EXISTS (
  SELECT
    FROM INFORMATION_SCHEMA.ROUTINES 
   WHERE SPECIFIC_SCHEMA = N'dbo'
     AND SPECIFIC_NAME = N'DD_AppendToFile' 
)
   DROP PROCEDURE dbo.DD_AppendToFile
GO
  
create procedure DD_AppendToFile    
@vchrText varchar(max),   
@vchrFileName varchar(255),   
@EOL varchar(10) = NULL
  
as
  
begin   
    if @EOL is NULL begin       
        set @EOL = char(13) + char(10);   
    end;   
      
    -- the period allows for empty lines   
    declare @prefix varchar(255) = 'echo.';   
  
    --  '>>' will append, use '>' to replace
    declare @suffix varchar(255) = ' >> ' + @vchrFileName;   
  
    -- Escape special characters so things work   
    -- But escapes work funny when in double quotes (and maybe single quotes too)   
    set @vchrText = (case when charindex('"', @vchrText) = 0 
                        then replace(replace(replace(@vchrText, '|', '^|'), '>', '^>'), '&', '^&')                    
                        else @vchrText
                        end);  
    set @vchrText = replace(@vchrText,'<','^<'
  
    while (@vchrText <> '') begin       
        declare @pos int = charindex(@EOL, @vchrText);       
        declare @line varchar(8000) = (case when @pos > 0 then left(@vchrText, @pos) else @vchrText end);       
        set @vchrText = (case when @pos > 0 then substring(@vchrText, @pos+2, 1000000) else '' end);       
        set @line = @prefix + @line + @suffix;       
  
        --write @line to file; 
        exec xp_cmdshell @line;   
    end;
end;  

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences