Friday, October 4, 2013

Extract Query Result in A Flat File (BCP command)

Please consider following script given below.

EXEC sp_configure 'show advanced options',1;
RECONFIGURE;

EXEC sp_configure 'Ad Hoc Distributed Queries',1;
RECONFIGURE;

EXEC sp_configure 'xp_cmdshell','1'
RECONFIGURE;
DECLARE @CMD VARCHAR(500) = 'BCP "SELECT col1, col2 FROM [MY_DB].[DBO].[MY_TABLE]" queryout C:\TestData.txt -t, -c -S' + @@ServerName+ ' -U user1 -P pwd@123 -T';


EXEC xp_cmdshell @CMD