3

I am having issue with the way results are displayed with a bcp export to csv.

The below works fine, but is comma delimited so won't work for what I need.

DECLARE @sql VARCHAR(8000)

SET @sql = 'bcp "SELECT * FROM db..viewname" queryout "C:\test.csv" -c –t, -T -S <SERVERNAME>'

EXEC master..xp_cmdshell @sql

Results:

enter image description here

But If I change the "," to a pipe (or anything else) it breaks.

DECLARE @sql VARCHAR(8000)

SET @sql = 'bcp "SELECT * FROM db..viewname" queryout "C:\test.csv" -c –t"|" -T -S <SERVERNAME>'

EXEC master..xp_cmdshell @sql

Results:

enter image description here

The view used is a simple column select from a table with a WHERE clause.

What am I missing here..?

4
  • 1
    Rename your output file to something other than .csv. Excel will always assume that it is comma-separated (Comma Separated Values), and automatically load it. If you call it .txt for example, and open it manually, you can tell Excel that it is pipe delimited and it will recognise the pipes and break up the data correctly.
    – DeanOC
    Nov 9, 2014 at 22:06
  • So there is no way to have it formatted in columns with a pipe delimiter by default? Does the .txt file need to be imported into Excel with pipe assigned as the delimeter after the initial export?
    – Jason
    Nov 9, 2014 at 22:26
  • 2
    Out-of-the-box Excel will not automagically open a pipe-delimited file in the same way that it (thinks it) knows how to open a csv file. You either do it manually, File|Open etc, or write a macro to do it if you're going to do it a lot. Is this issue only to do with the way that Excel shows the data, or do you have a problem with the data export itself?
    – DeanOC
    Nov 9, 2014 at 22:57
  • In that case this seems to be an issue with my lack of Excel knowledge. The data export is fine and working as intended in that case. I export to .txt, import as data through Excel and use a pipe delimiter and all is well. Thanks for the help!
    – Jason
    Nov 9, 2014 at 23:02

1 Answer 1

3

I know this is an old question but I just ran into this problem yesterday. To add a pipe delimiter you need to escape the pipe with a carrot like so:

-t^|

So set your @SQL like so:

SET @sql = 'bcp "SELECT * FROM db..viewname" queryout "C:\test.csv" -c –t^| -T -S <SERVERNAME>'

Hope this helps someone. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.