Skip to main content

Posts

Showing posts from December, 2009

BCP to export result set into CSV

BCP is used in SQL server either exports data to external files or imports data from external files (.txt, .csv etc). You can execute the bcp utility form command prompt (cmd) and T-SQL, further you can schedule the job to do the bcp task on regular basis, if required. See an example of BCP using T-SQL: declare @sqlI2 varchar ( 8000 ) declare @pathI2 varchar ( 100 ) SET @pathI2 = 'C:\Data' + Convert ( Varchar ( 50 ), GetDate (), 105 ) + '.csv' select @sqlI2 = 'bcp "SELECT ''Id'' AS ID , ''Name'' AS Name,''Date'' AS Date UNION ALL SELECT CONVERT(Varchar(10),Id) AS ID, Name,CONVERT(Varchar(50),GetDate()) AS Date FROM TEST..Employee" queryout ' + @pathI2 + ' -c -t, -U sa -P sa -S AKSSRV' exec master .. xp_cmdshell @sqlI2 Just set the SQL statement, location of output path, SQL server name, user id and password and execute the code. The output of file is copie...