问题描述
是否可以在存储过程中使用sql脚本将记录导出为csv格式?
我正在尝试制定工作计划,该计划会将记录导出到.csv
文件中。我正在使用sql Server 2012。
我不想为导出而制作小型应用程序。这就是为什么我要制作一个脚本并将其按计划添加的原因。例如,我有类似
的记录EmpID EmployeeName TotalClasses
---------------------------------
01 Zaraath 55
02 John Wick 97
文件目标位置为D:/ExportRecords/file.csv
解决方法
在SSMS中,您可以将查询结果保存为CSV格式。
在下面的查询中尝试此操作
-- To allow advanced options to be changed.
EXECUTE sp_configure 'show advanced options',1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXECUTE sp_configure 'xp_cmdshell',1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
declare @sql varchar(8000)
select @sql = 'bcp "select * from DatabaseName..TableName" queryout d:\FileName.csv -c -t,-T -S' + @@servername
exec master..xp_cmdshell @sql
您必须在FileName.csv
中创建空D:\
您可以使用BCP(大容量复制程序)内置的cli从SQL Server导出数据。它的开销很低,执行速度很快,并且具有许多功能开关,例如-t(可创建CSV文件),非常适合脚本编写。
类似这样的事情。 Docs也很有用
BCP dbo.YourTable out D:/ExportRecords/file.csv -c -t