2012-02-16 17 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