SQL BCP with column name

天涯浪子 提交于 2021-02-20 04:44:07

问题


I am trying to export my stored procedure to a .csv file using BCP. It does give me a output file in .CSV but it does not print column name. Below is the script. Please look at and let me know what i am missing

    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

回答1:


The easiest thing to do is do a union all with the column names when you are using queryout.

so an example is provided below.

select 'col1','col2',col3','col4' ... etc
union all
select col1,col2,col3,col4 ... etc from yourtable



回答2:


After a lot of trail and error below is the answer on how to add column

First create a header.txt file (inside the header file add all of you header) for example if the header file need firstname, lastname etc

second paste the below query in your stored procedure

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


来源:https://stackoverflow.com/questions/46347264/sql-bcp-with-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!