小编典典

具有列名称的SQL BCP

sql

我正在尝试使用BCP将存储过程导出到.csv文件。它确实为我提供了.CSV格式的输出文件,但它不显示列名。下面是脚本。请看看,让我知道我在想什么

    DECLARE @command VARCHAR(4000)
    declare @fulldate varchar(30) = convert(varchar,GETDATE(),112)
    declare @year varchar(30) = left(@fulldate,4)
    declare @day  varchar(30) = right(@fulldate,2)
    declare @month varchar(30) = left(right(@fulldate,4),2)
    DECLARE @FileDirectory VARCHAR(1000) = 'c:\'
    DECLARE @FileName VARCHAR(255)= 'TestingDOC' + @month + '.' + @day + '.'      + @year  + '.txt'
    declare @attach varchar(1255) = @fileDirectory + @fileName

    SET @command = 'bcp "select * from ngprod.dbo.TEMP_PAS"'
        + ' queryout "' + @FileDirectory + @FileName + '"'
        + ' -c -t, -T -S'+ @@servername
    EXEC master..xp_cmdshell @command

阅读 206

收藏
2021-05-16

共1个答案

小编典典

经过大量的跟踪和错误之后,下面是有关如何添加列的答案

首先创建一个header.txt文件(在头文件中添加所有头文件),例如,如果头文件需要名字,姓氏等

第二,将以下查询粘贴到您的存储过程中

DECLARE @command VARCHAR(4000)

DECLARE @FileDirectory VARCHAR(1000) = 'c:\test\'

DECLARE @HeaderFile varchar(255) = 'Headers.txt'

DECLARE @FileName VARCHAR(255)

SET @FileName = 'TestFile_' + CONVERT(VARCHAR,GETDATE(),112)

SET @command = 'bcp "select * from TESTDB.dbo.TEST_Table"'

       + ' queryout "' + @FileDirectory + @FileName + '.txt"'

       + ' -c -q -t, -T  -S'+@@servername

EXEC master..xp_cmdshell @command

SET @command =  'copy "' + @FileDirectory + @HeaderFile + '"+"' + @FileDirectory + @FileName + '.txt"' +  ' "' + @FileDirectory + @filename + '.csv"'

EXEC master..xp_cmdshell @command

SET @command = 'del "' + @FileDirectory + @FileName + '.txt"'

EXEC master..xp_cmdshell @command
2021-05-16