Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UNION FOR XML name output column

I'm trying to generate an XML output from SQL and need to use a UNION statement and also name the output column.

I had this working before when I didn't need to use a UNION statement using:

select(
SELECT

    [CompanyName],
    [Address1],
    [Address2],
    [Address3],
    [Town],
    [County],
    [Postcode],
    [Tel],
    [Fax],
    [Email],
    [LocMap]

FROM [UserAccs] FOR XML PATH ('AccountDetails'), root ('Root') 
) as XmlOutput

Which named the output XML column as XmlOutput

I am now trying:

select(
SELECT

    [CompanyName],
    [Address1],
    [Address2],
    [Address3],
    [Town],
    [County],
    [Postcode],
    [Tel],
    [Fax],
    [Email],
    [LocMap]

FROM [UserAccs]

UNION

SELECT

    [CompanyName],
    [Address1],
    [Address2],
    [Address3],
    [Town],
    [County],
    [Postcode],
    [Tel],
    [Fax],
    [Email],
    [LocMap]

FROM [UserAppAccs]



 FOR XML PATH ('AccountDetails'), root ('Root')
) as XmlOutput

But receive an error message, does anyone know a way around this?

The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table syntax and apply FOR XML on top of it.

Thanks J.

like image 654
Jammer Avatar asked Feb 16 '12 12:02

Jammer


People also ask

Can you UNION columns in SQL?

Using UNION on Multiple FieldsWe can apply UNION on multiple columns and can also order the results using the ORDER BY operator in the end. This will result in the following: The result is sorted according to the “Dept_ID.” We can also filter the rows being retrieved by each SELECT statement.

How can I get SQL query results in XML?

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.

What is for XML path 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.


1 Answers

Wrap your 2 selects on a single one like so:

select (
    select id, name from (
        select id, name 
        from xmltest 
        UNION
        select id, name 
        from xmltest 
    ) A
    FOR XML PATH ('AccountDetails'), root ('Root')
) As XmlOutput
like image 78
Diego Avatar answered Sep 25 '22 09:09

Diego