Archive for category Shell Command
Create Excel file with dynamic file names using BCP in SQL Server 2008 R2
Posted by Shipra Gupta in CodeProject, Shell Command, SQL Server on September 25, 2014
We can export data returned from SQL Server query or Procedure to Excel or txt/csv format with dynamic file names or path using SSMS Data Export or SSIS Package or by using BCP command as discussed in this article.
Configuration required to execute shell commands:
EXEC sp_configure ‘show advanced options’, 1
RECONFIGURE WITH OVERRIDE
GO
EXEC master.dbo.sp_configure ‘xp_cmdshell’, 1
RECONFIGURE WITH OVERRIDE
GO
declare @filePath varchar(500), @ssql varchar(max)
select @filePath=‘D:\Excel\Data_’+ CONVERT(varchar,getdate(),105) + ‘.xls’
set @ssql=‘EXEC xp_cmdshell ”BCP “exec MyDB.dbo.usp_GetExcelData 1” queryout “‘ + @filePath + ‘” -c -S 172.24.1.11 -T”’
exec(@ssql)
Here MyDB.dbo.usp_GetExcelData denotes SQL procedure name to be executed.
The path can have from 1 through 255 characters.
The data file can contain a maximum of 263 – 1 rows.
For more information on BCP command options to import and export data into various formats, Please refer:
http://msdn.microsoft.com/en-IN/library/ms162802.aspx
This feature is very useful, in case some exportable reports are required and data is heavy. So instead of putting load on web server, one can create the excel file by calling such proc in a job and saving file creation time.
Njoy 🙂
Recent Comments