解决bcp导出CSV文件没有表头

思路:

1.输出表头文件到指定目录

2.bcp导出csv文件到temp目录

3.将以上导出文件与表头文件合并

4.删除temp目录下的文件

实现:

create   proc   exportCSV
(
    @id int  ,@filepath varchar(8000),--输入参数
    @re int output --输出参数
)
  as   
    declare   @s   varchar(8000)
    --csv文件的表头,你也可以自定义表头,但是为了与前端d3.js访问,直接就data1,data2了set @s='echo data1,data2>"'+@filepath+'"' 
    exec   master..xp_cmdshell  @s,no_output 
    --导出csv文件到temp目录
    set   @s='bcp   "exec 数据库名..queryUserAnsawer '+cast(@id as varchar(50))+'" queryout "'+'"%temp%\temp.csv"'+'"   /c /t,  /U"登录名"   -P"密码" /S 服务器名'     
    exec   master..xp_cmdshell   @s ,no_output 
    --将temp目录下的csv文件与之前的csv文件的表头合并
    set @s='more %temp%\temp.csv >>"'+@filepath+'"'
    exec   master..xp_cmdshell   @s ,no_output 
    --删除temp目录下的csv文件
    exec   master..xp_cmdshell   'del %temp%\temp.csv' ,no_output 
    --返回执行结果
    set @re=1 --如果可以执行这一句代表之前的语句没有报错
go

--调用存储过程exportUserAnsawer
 --F:\Data\data.csv
declare @w int
exec 数据库名..exportCSV 5, 'F:\Data\data.csv' ,@w output
--PRINT '执行结果:'+CONVERT(varchar(20),@w)
select @w as '返回值'

同理,bat实现与sh实现也一样,我就不写了 。

猜你喜欢

转载自www.cnblogs.com/feiquan/p/10843151.html
今日推荐