2012-10-04 48 views
0

給定兩個表:多列XML列

T1(EntityID int , EmailAddress varchar(55),MaxNumberOfConnections int)

T2(EntityID int , EntityAttributes XML)

如何插入從T1所有的數據到T2用一個語句以這樣的方式,所有的列T1(除EntityID之外)都轉換爲T2中的一個XML列:

T1(1,'[email protected]',454) 

T2(1, '<Attributes> 
      <Attribute EmailAddress="[email protected]"> 
      <Attribute MaxNumberOfConnections ="454"> 
     </Attributes>') 
+0

是否XML需要在正是格式?通過重用元素Attribute,但使用不同的屬性,您可以爲同一個名稱提供不同的定義。你可以將多個屬性(對於字段)組合成單個Attribute元素,還是使用EmailAddress,MaxNumberOfConnections等元素? –

+0

XML架構不必與我在這裏展示的完全一樣。 – mcl

+0

然後發佈您的確切架構,那麼您如何獲得令人滿意的答案? – Yaroslav

回答

1

這裏是基於我的評論兩種解決方案 - 單「屬性」元素具有多個屬性:

SELECT 
    EntityId, 
    (
     SELECT 
      EmailAddress AS [Attribute/@EmailAddress], 
      MaxNumberOfConnections AS [Attribute/@MaxNumberOfConnections] 
     FROM 
      T1 i 
     WHERE 
      i.EntityId = o.EntityId 
     FOR XML PATH('Attributes') 
    ) AS EntityAttributes 
FROM 
    T1 o 

每個字段的單個元素:

SELECT 
    EntityId, 
    (
     SELECT 
      EmailAddress, 
      MaxNumberOfConnections 
     FROM 
      T1 i 
     WHERE 
      i.EntityId = o.EntityId 
     FOR XML PATH('Attributes') 
    ) AS EntityAttributes 
FROM 
    T1 o