Search code examples
sql-servercsvt-sqlexport-to-csvbcp

Ignore null's in exported .csv file, bcp utility


How can I ignore null's in my exported .csv file, I used bcp utility within sql server, here it is how this looks like altogether.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID ('[dbo].[generateCSV]') IS NOT NULL
DROP PROCEDURE [dbo].[generateCSV]
GO

  CREATE PROCEDURE [dbo].[generateCSV]

(
 @table varchar(100),
 @output varchar(100), 
 @date varchar(12),
 @server varchar(30)
)

AS

DECLARE @sql varchar(8000)

SELECT @sql = 'bcp "select * from ' + DB_NAME() + '.dbo.' + @table  + ' 
where reportingdate = ''' + @date + '''"' + ' queryout ' +  @output + '  -c 
-C65001 -t";" -r"\n" -T -S' + @server 

 exec master..xp_cmdshell @sql 




       -- Main EXEC

EXEC dbo.generateCSV @table = 'Clients', @date = '2017-10-31', @output = 
'//172.18.16.109/share/Test.csv (server with export target location ) ', 
@server = '172.18.16.108(server we are connected to and from which we are 
taking the data)' 

After exporting and opening my file in notepad++ empty columns end up filled with NULL's.

enter image description here

What I want it to look like is...

enter image description here


Edit:

I included ISNULL() in my select clause but still notepad will read those columns as null valued.

SELECT @sql = 'bcp "select 
ReportingDate,uniqClientID,registrationNumber,name,ISNULL(vatNumber,'''') as 
vatNumber,ISNULL(entityStatusCode,'''') as entityStatusCode, 
maximumLifetimeDPD from ' + DB_NAME() + '.dbo.' + 
@table  + ' where ReportingDate = ''' + @date + '''"' + ' queryout ' +  
@output + '  -c -C65001 -t";" -r"\n" -T -S' + @server 

Solution

  • SELECT @sql = 'bcp "select * from ' + DB_NAME() + '.dbo.' + @table + ' where reportingdate = ''' + @date + '''"' + ' queryout ' + @output + ' -c -C65001 -t";" -r"\n" -T -S' + @server

    Instead of SELECT * write the specific column names.

    Wherever you feel NULL can appear you can write like following.

    ....   
    SELECT 
    Column1,
    ISNULL(Column2,'') AS Column2,
    Column3,
    ....
     from ' + DB_NAME() + '.dbo.' + @table 
    .....
    

    Note: If you have INT as datatype, you need to slightly change your select according to following query.

    DECLARE @INTVAL INT
    SET @INTVAL = NULL
    SELECT
    ISNULL(LTRIM(NULLIF(@INTVAL, 0)), '') AS ColumnName