【问题标题】:Append header and Footer to the csv data将页眉和页脚附加到 csv 数据
【发布时间】:2012-07-27 14:11:54
【问题描述】:

我需要使用存储过程将数据导出到 CSV。我正在使用bcp.exe 实用程序导出数据

select @sql = 'bcp dbo.Customers out c:\bcp\customers.txt -c -t, -T -S'+ @@servername
exec master..xp_cmdshell @sql

我需要在 CSV 的末尾添加包含列名和文本 File Ended' 的标题。

表结构是这样的

ID    Name
 1    'joe'
 2    'jon'

在 CSV 中应该是这样的

ID,Name
1,joe
2,jon
END_OF_FILE

我创建了一个包含列标题和数据的视图

select 'ID' as ID , 'Name' as Name 
union all 
select ID, Name from Customer

我需要在 CSV 末尾附加 File Ended

任何想法将不胜感激

【问题讨论】:

    标签: sql-server-2008 csv


    【解决方案1】:
    select 'ID' as ID , 'Name' as Name 
    union all 
    select cast(ID as varchar(max)), Name from Customer
    union all
    select 'End of file', ''
    

    甚至更好:

    SELECT 'ID, Name' as line
    UNION ALL
    SELECT cast(ID as varchar(max))+', '+Name FROM Customer
    UNION ALL
    SELECT 'End of file'
    

    【讨论】:

      【解决方案2】:

      您需要进行更多处理。例如,这些 DOS 命令将创建一个带有页眉和页脚的文件 customers2.txt

      echo Header Line > c:\bcp\customers2.txt
      type c:\bcp\customers.txt >> c:\bcp\customers2.txt
      echo Footer Line >> c:\bcp\customers2.txt
      

      【讨论】:

        猜你喜欢
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 2018-09-14
        • 1970-01-01
        • 2018-08-17
        相关资源
        最近更新 更多