1

I want to generate a .CSV file based on data in a datatable. I know this question has been asked before, but I can't find any examples of how to specify what the separator should be.

For example if I have a table and a query like this, this is what I want the output to be:

MyTable:

Id - Int Key
NickName- NvarChar
REALName - NvarChar
Number - NvarChar
Updated - bit

Query:

SELECT * 
FROM MyTable 
WHERE Updated = 1

Output:

I want my output to use | as the field separator. So the output in the CSV file will look something like this:

Id|NickName|REALName|Number|Updated
1|NickNameHere|RealNameHere|0798548558|1
2|NickNameHere2|RealNameHere2|079948558|1

and so on.

2
  • 1
    Are you using 3 different versions of SQL Server? Commented Feb 21, 2017 at 17:58
  • 1
    Use BCP to create the CSV file. Commented Feb 21, 2017 at 18:23

1 Answer 1

1

The following query generate CSV data with '|' separator

select 'Id|NickName|REALName|Number|Updated'
union all
select
       cast (Id as nvarchar) + '|'
       + NickName  + '|'
       + RealNameHere  + '|'
       + Number + '|'
       + cast (Updated as nvarchar)
    from MyTable 
    WHERE Updated = 1

Saving output results to TextFile:

Method 1: from within SSMS

From ssms menu: query -> results to -> results to file

Method 2: using Powershell Invoke-SqlCmd

 Invoke-SqlCmd -Query "your query" | Export-Csv "path\to\csvfile"

Method 3: using SqlCmd command line tool:

sqlcmd -q "your query" -o "path\to\csvfile" -S server -P password -d database
Sign up to request clarification or add additional context in comments.

1 Comment

but how do I get that to output/create a CSV file, surely this is just the select.

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.