Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to export sql data to csv using bcp

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?

like image 377
psysky Avatar asked Jun 17 '17 16:06

psysky


2 Answers

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
like image 94
Ven Avatar answered Nov 20 '22 10:11

Ven


Bcp queryout option should be used.

Syntax would be:

SET @sql = 'bcp "SELECT [vl]
            ,[data]
            ,[URL]
            ,[parse]
            ,[Strata]
            ,[Id]
        FROM [dbo].[ClearDB] 
        WHERE [data] > ''01.05.2017''
        AND NOT [vl] =''mag''
        AND NOT [vl] =''Maxximo''" 
    queryout c:\csv\comm.txt
    -c -t, -T -S '+ @@servername + '\' + @@servicename
like image 25
Mukesh Avatar answered Nov 20 '22 10:11

Mukesh