忽略导出的.csv文件中的null,即bcp实用程序

时间:2018-02-05 10:46:00

标签: sql-server csv tsql export-to-csv bcp

  

如何在导出的.csv文件中忽略null ,我使用了bcp实用程序   在sql server中,这就是它的外观。

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)' 

在notepad ++中导出并打开我的文件后,空列最终填满了NULL。

enter image description here

我希望它看起来像......

enter image description here

修改

我在select子句中包含了 ISNULL(),但仍然记事本会将这些列读为空值。

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 

1 个答案:

答案 0 :(得分:1)

  

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

而不是SELECT *写出特定的列名。

无论您感觉NULL出现在哪里,您都可以写下以下内容。

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

注意:如果您有INT作为数据类型,则需要根据以下查询稍微更改您的选择。

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