【问题标题】:SQL UNION FOR XML name output columnSQL UNION FOR XML 名称输出列
【发布时间】:2012-02-16 12:22:35
【问题描述】:

我正在尝试从 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

将输出 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

但是收到一条错误消息,有没有人知道解决这个问题的方法?

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.

谢谢 J.

【问题讨论】:

  • 错误信息是什么意思?

标签: sql-server sql-server-2008 tsql sqlxml


【解决方案1】:

将您的 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

【讨论】:

  • 我不明白你要我尝试什么。
  • 我认为除了 UNION 标记之外,for xml 仅应用于第二个查询(解析事物)。也许如果您将两个查询都指定为一个,它将起作用
  • 好的,如果你像我的例子一样运行测试,你会发现它会起作用
  • 谢谢 Diego,是的,似乎已经做到了...我只需要在末尾添加“As XmlOutput”,因为它是最重要的输出列的命名。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
相关资源
最近更新 更多