I am trying to write to a file with Transact-SQL using a stored procedure that I can pass input to. However, every time I run the commands in SQL Server 2012 it displays Command(s) completed successfully.
, but I navigate to the text file and I don't see any text there. Any idea what could be going wrong?
My code:
-- GRANTS PERMISSION TO OLE AUTOMATION -- sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1; GO RECONFIGURE; GO DROP PROC WriteToGSQL; -- ENCAPSULATING THE SPECIFIC CODE THAT DOES THE ACTUAL WRITING TO THE TEXT FILE -- SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROC [dbo].[WriteToGSQL] @Path VARCHAR(2000), @Text VARCHAR(2000) AS BEGIN DECLARE @Auto INT DECLARE @FileID INT EXECUTE sp_OACreate 'Scripting.FileSystemObject', @Auto OUT EXECUTE sp_OAMethod @Auto, 'OpenTextFile', @FileID OUT, @Path, 8, 1 EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, @Text EXECUTE sp_OADestroy @FileID EXECUTE sp_OADestroy @Auto END DECLARE @File VARCHAR(2000); DECLARE @Txt VARCHAR(2000); SET @File = 'C:\xxxxxxxx\xxxx\test.txt'; SET @Txt = 'Did it work?'; EXEC WriteToGSQL @File, @Txt;
sp_OACreate
andsp_OAMethod
, so there's no way to see if anything's going wrong. Use the return value in conjunction withsp_OAGetErrorInfo
. See MSDN for a sample. – Jeroen MostertClose
on the text file. Simply callingsp_OADestroy
gets rid of the object and may prevent the stream from flushing its contents. (I have no experience actually using it, so this is speculation.) – Jeroen Mostert