SQL UNION FOR XML名称输出列

JBo*_*oom 14 t-sql sql-server sqlxml sql-server-2008

我正在尝试从SQL生成XML输出,需要使用UNION语句并命名输出列.

我之前有这个工作,当我不需要使用UNION语句时:

select(
SELECT

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

FROM [UserAccs] FOR XML PATH ('AccountDetails'), root ('Root') 
) as XmlOutput
Run Code Online (Sandbox Code Playgroud)

将输出XML列命名为XmlOutput

我现在正在尝试:

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
Run Code Online (Sandbox Code Playgroud)

但收到错误信息,有没有人知道这方面的方法?

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.
Run Code Online (Sandbox Code Playgroud)

谢谢J.

Die*_*ego 24

将2个选项包装在一个选项上,如下所示:

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
Run Code Online (Sandbox Code Playgroud)