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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With