how to export sql data to csv using bcp

D.Joe picture D.Joe · Jun 17, 2017 · Viewed 23.3k times · Source

I use simple code

declare @sql varchar(8000) 
select @sql  = 'bcp ExcelAnalysis.dbo.ClearDB out c:\csv\comm.txt -c -t, -T -S '+ @@servername 
exec master..xp_cmdshell @sql 

but this code export all my table, but i need only some fields and conditions like:

declare @sql varchar(8000) 
select @sql = 'bcp 
SELECT 

      ,[vl]
      ,[data]
      ,[URL]
      ,[parse]
      ,[Strata]
      ,[Id]
   FROM [ExcelAnalysis].[dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ="mag"and NOT [vl] ="Maxximo"   out c:\csv\status.txt -c -t, -T -S '+ @@servername 
exec master..xp_cmdshell @sql 

but if i use any fields, the bcd returns message with his syntax. How do correct?

Answer

Ven picture Ven · Jun 17, 2017

First Part : Create a view in database and second part to execute statement to get results into CSV.Let me know if you need more help

use [ExcelAnalysis].
go
;

create view [dbo].[vw_ClearDB] as
SELECT 

      [vl]
      ,[data]
      ,[URL]
      ,[parse]
      ,[Strata]
      ,[Id]
   FROM [dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ='magand'
   NOT [vl] ='Maxximo'

   GO

   ;


declare @sql varchar(8000) 
select @sql  = 'bcp ExcelAnalysis.dbo.vw_ClearDB out c:\csv\comm.txt -c -t, -T -S '+ @@servername 
exec master..xp_cmdshell @sql