Export to CSV with Column names

Posted on 2014-10-30
Last Modified: 2014-10-30
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)
declare @s varchar(5000)
set @s = 'bcp "'+ @SQL + '" queryout ' + @FilePath + ' -c -t, -T'
exec master..xp_cmdshell @s
print @s
Question by:JElster
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
LVL 24

Accepted Solution

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'

Author Comment

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

Expert Comment

by:Phillip Burton
ID: 40413896

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

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 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.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
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.

726 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