0

I have an SQL query that returns some rows. How can I change it so that the output of the query is in CSV format?

I have found a way to make the result in XML format, but because of the nature of XML the result is too large to be useful.

The query is very large (and it's not really important), so I wont post it here. Here is a link to it.Link

I don't want the SQL query to save the result as a CSV file.
3
  • I misread that, and apologize. Commented Jul 21, 2017 at 14:24
  • Question, is this a one time query or will you need to run this multiple times? Commented Jul 21, 2017 at 20:52
  • Multiple times, programmatically. Commented Jul 25, 2017 at 15:14

2 Answers 2

1

YES

try this

DECLARE  @query nvarchar(max)

select @query = STUFF(  (SELECT N',' + cast( id as nvarchar)  
from TableX 
--some WHERE clause here as well

FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')  ,1,1,'')

select  @query

NO variable :

 select   STUFF(  (SELECT N',' + cast( id as nvarchar)  
 from TableX 
 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')  ,1,1,'')
Sign up to request clarification or add additional context in comments.

1 Comment

This is not a complete solution. You only have this set up to work for id field. If you look at the link provided @user3465882 has some fields that could have commas and double quotes. Also, you don't include the headers for the columns. See en.wikipedia.org/wiki/Comma-separated_values for some standard rules.
0

Like this:

select field1
, '","'
, field2
, '","'
etc

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.