Ray
Ray

Reputation: 3449

Basic sql: Outputting headers surrounded by double quotes

I'm thinking that this is pretty easy to do. Say I have the following query:

select QUOTENAME(countNumber as [Count Number],'"'), QUOTENAME(testValue,'"') as [Test Value] from tblTestResults

I get my results surrounded by double quotes - good. But now when I choose "Save as", not only do I want the headers, but I want them surrounded by double quotes as well in my resulting csv file. I saw (from another stackoverflow question) that there should be an option to select headers in Tools > Query Results. But I don't seem to have that in mine. Thoughts?

Also, I'm using Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)

Upvotes: 2

Views: 1571

Answers (2)

codingbiz
codingbiz

Reputation: 26386

As @Aaron Bertrand mentioned, you cannot include headers when doing Save As

if your header is static (i.e. known before hand, then this would do). Though i am not very clear what you want to achieve

select "CountNumber", "TestValue"
UNION ALL
select QUOTENAME(countNumber as [Count Number],'"'), QUOTENAME(testValue,'"') as [Test Value] from tblTestResults

Simpy means

Your column headers
UNION ALL
Your results

This makes your columns as part of the rows so you can export them to CSV. The first row now contains your columns. Don't forget to add your QUOTENAME(...) where necessary

Upvotes: 0

Aaron Bertrand
Aaron Bertrand

Reputation: 280260

SELECT TOP (1) QUOTENAME(name, '"') AS ["Name"]
FROM sys.objects ORDER BY [object_id];

Yields this:

"Name"
"sysrscols"

If you click in the top-left corner of the grid output (so all rows are selected), you can right-click and select "Copy with Headers" ... this will copy the headers with the quotes as per above.

Query > Results to File should show these headers with double quotes as well (but not Save Results As for some reason - it doesn't include the headers).

Upvotes: 3

Related Questions