思路:
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實現也一樣,我就不寫了 。