2012-02-16 43 views
8

我试图从SQL生成XML输出,并且需要使用UNION语句并命名输出列。用于XML名称输出列的SQL 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.

+1

是什么错误消息说? – Mithrandir 2012-02-16 12:31:44

+0

上面的错误消息...谢谢 – JBoom 2012-02-16 12:53:27

回答

15

包裹在一个单一的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 
+0

我没有得到你要求我尝试的东西。 – JBoom 2012-02-16 13:09:48

+0

我认为除了UNION标签之外,for xml仅适用于第二个查询(解析事件)。也许如果你指定两个查询为一个,它将起作用 – Diego 2012-02-16 13:11:37

+0

为什么downvote?我只是跑了一个测试,它完美的工作 – Diego 2012-02-16 13:15:17