Solved

Export to CSV with Column names

Posted on 2014-10-30
3
170 Views
Last Modified: 2014-10-30
Hi.
I have the following. How can I export to CSV and include the column names in the first row of the CSV file?
Any ideas

The following works but does not include the column names.

ALTER  procedure [dbo].[EXPORT_TO_CSV]
(
 @SQL NVARCHAR(4000), @FilePath nVARCHAR(200)
)
as
BEGIN
declare @s varchar(5000)
set @s = 'bcp "'+ @SQL + '" queryout ' + @FilePath + ' -c -t, -T'
exec master..xp_cmdshell @s
print @s
END
0
Comment
Question by:JElster
  • 2
3 Comments
 
LVL 24

Accepted Solution

by:
Phillip Burton earned 500 total points
ID: 40413854
I suggest you use a UNION ALL,

such as

bcp "select 'Column1', 'Column2', 'Column3' "'+ @SQL + '" queryout ' + @FilePath + ' -c -t, -T'
0
 
LVL 1

Author Comment

by:JElster
ID: 40413895
So your saying I need to manually add the field names and then do a union all?
0
 
LVL 24

Expert Comment

by:Phillip Burton
ID: 40413896
Yes.
0

Featured Post

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question