在bcp .csv文件导出

时间:2016-09-16 03:10:45

标签: sql-server tsql csv

DECLARE @CMD varchar(4000),
        @DelCMD varchar(4000),
        @HEADERCMD varchar(4000),
        @Combine varchar(4000),
        @Path varchar(4000),
        @COLUMNS varchar(4000)

-- Set values as appropriate
SET @COLUMNS = ''
SET @Path = '\\servername\share\outputpath'

-- Set up the external commands and queries we'll use through xp_cmdshell
-- Note that they won't execute until we populate the temp tables they refer to
SET @CMD = 'bcp "select * from ##OutputTable" queryout "' + @Path + '\Temp_RawData.csv" -S ' + @@SERVERNAME + ' -T -t , -c'
SET @HEADERCMD = 'bcp "SELECT * from ##cols" queryout "' + @Path + '\Temp_Headers.csv" -S ' + @@SERVERNAME + ' -T -t , -c'
SET @Combine = 'copy "' + @Path + '\Temp_Headers.csv" + "' + @Path + '\Temp_RawData.csv" "' + @Path + '\MyCombinedFile.csv"'
SET @DelCMD = 'del "' + @Path + '\Temp_*.csv"'

-- Create and populate our temp table with the query results
SELECT
  * INTO ##OutputTable
FROM YourSourceTable

-- Generate a list of columns   
SELECT
  @COLUMNS = @COLUMNS + c.name + ','
FROM tempdb..syscolumns c
JOIN tempdb..sysobjects t
  ON c.id = t.id
WHERE t.name LIKE '##OutputTable%'
ORDER BY colid

SELECT
  @COLUMNS AS Cols INTO ##Cols

-- Run the two export queries - first for the header, then for the data
EXEC xp_cmdshell @HEADERCMD
EXEC xp_cmdshell @CMD

-- Combine the two files into a single file
EXEC xp_cmdshell @Combine

-- Clean up the two temp files we created
EXEC xp_cmdshell @DelCMD

-- Clean up our temp tables
DROP TABLE ##cols
DROP TABLE ##OutputTable

我使用此脚本将.csv文件导出到我的路径。但是它适用于非null值。如果结果集包含任何空值,则格式化将崩溃。我们如何处理bcp中的空值。请建议

0 个答案:

没有答案