Saturday, June 21, 2008

Write Query Results Directly to File


DECLARE @FileName varchar(50),
@bcpCommand varchar(2000)

--The character after -t notes the field delimeter. If -t is removed tab is the default.

SET @FileName = REPLACE('c:\Test_'+CONVERT(char(8),GETDATE(),1)+'.txt','/','-')

SET @bcpCommand = 'bcp "SELECT * FROM sysfiles" queryout "'
SET @bcpCommand = @bcpCommand + @FileName + '" -T -c -t,'

EXEC xp_cmdshell @bcpCommand

0 comments: