?
Solved

Export to CSV with Column names

Posted on 2014-10-30
3
Medium Priority
?
198 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
[X]
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
  • 2
3 Comments
 
LVL 24

Accepted Solution

by:
Phillip Burton earned 2000 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

Get MySQL database support online, now!

At Percona’s web store you can order your MySQL database support needs in minutes. No hassles, no fuss, just pick and click. Pay online with a credit card.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
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.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Suggested Courses

762 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