Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing a FOR XML PATH result

I want to alias the output of the following:

-- Test table with some rubbish data
DECLARE @Test TABLE
(
    Names [varchar](20)
)
INSERT INTO @Test
SELECT 'Simon'

-- Query returns but with XML_<GUID> alias
SELECT 
    Names
FROM 
    @Test t 
FOR XML PATH ('Test')

So rather than a column header of XML_GUID I want to give it an alias of say 'Test' for sake of argument. I can't seem to get it. Anyone know how? I tried following an example from here: http://social.msdn.microsoft.com/Forums/nl/sqlxml/thread/1605c722-6388-40ff-9ab5-a3817a1db81f but I can't seem to get it to return. I always run into the error that says the is no name for column 1.

Any help appreciated.

Thanks,

Simon

like image 742
Simon Osborne Avatar asked Jan 17 '13 13:01

Simon Osborne


People also ask

What does for XML Path do in SQL?

We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.

Which of the following modes do you specify in a FOR XML clause?

In a FOR XML clause, you specify one of these modes: RAW. AUTO. EXPLICIT.

What is the proper syntax for aliasing a field?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];

What of the following clause used with select query will return the result of the query as XML form?

A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.


1 Answers

Make it a subquery:

select (
SELECT 
    Names
FROM 
    @Test t 
FOR XML PATH ('Test'),TYPE) as Test

Subqueries produce values but never provide a name for a column. I also specified ,TYPE because otherwise it forces a conversion to varchar(max) on the result, whereas you presumably want to keep it as xml.

like image 185
Damien_The_Unbeliever Avatar answered Sep 29 '22 11:09

Damien_The_Unbeliever