I am looking for a way to dynamically get the headers from a table without having to write them (select 'header1' as "header1"…., 'header50' as "header50" from MyTable)
It doesn't work above a certain number of columns, and/or the fixed limit of characters in a query
The goal is to export the headers and the data from the table to a text file or an excel file with a BCP command.
Can you help me out, please ?
Best Answer
If using
xp_cmdshell
andPowershell
is an option (rather thanBCP
), you could achieve your goal as follows:A possible downside to this approach is because ConvertTo-CSV automatically surrounds output columns with double quotes. The follow script handles the elimination of ALL double quotes. This could be problematic if your data actually contains double quotes.
Note that the
ConvertTo-Csv
cmdlet allows you to specify a Delimiter. If you don't provide that parameter, the default is a comma (as represented by the output below.Results in C:\Test\test.txt:
Here is an example where I'm using backtick t (`t) to export a tab delimited file.