Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Export to CSV with Column names

Posted on 2014-10-30
3
174 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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

838 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