SQL UNION FOR XML name output column

痞子三分冷 提交于 2019-12-18 18:56:40

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/9311198/sql-union-for-xml-name-output-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!