Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 SSIS and Import/Export (2005)
 Include Column Names in .CSV file via BCP

Author  Topic 

qman
Constraint Violating Yak Guru

442 Posts

Posted - 2009-03-10 : 07:59:26
I have a SQL 2005 Job which calls a Stored Procedure.
Within this SP, I write a query result out to a .CSV file using BCP commands.

My question: How can I add header/column names to row 1 of the .CSV file followed by the data in row 2, etc.?

My BCB code is shown below:

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @cmd as varchar(300)
DECLARE @today as varchar(20)
set @today = CONVERT(char(8), GETDATE(), 112)
set @cmd = 'bcp "exec usp_create_company_list_for_export" queryout "c$\test\test_' + @today + '.csv" -U aaa -P bbb -c -t"0x7C"'
EXEC master..xp_cmdshell @cmd
set @cmd = 'bcp "exec usp_create_company_list_for_export" queryout "c$\test\log\test_LOG_' + @today + '.csv" -U aaa -P bbb -c -t"0x7C"'
EXEC master..xp_cmdshell @cmd
-- print @cmd
END

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-10 : 14:29:35
use INFORMATION_SCHEMA.COLUMNS view to get column details as shown below

http://sqlblogcasts.com/blogs/madhivanan/archive/2008/10/10/export-to-excel-with-column-names.aspx
Go to Top of Page
   

- Advertisement -