2014-04-30 58 views
1

我有一個表中的兩個XML字段說A和B A有類似的數據:和寫入到另一個XML領域的SQL Server

   <periods> 
       <historicalperiod>2</historicalperiod> 
       <historicalperiod>4</historicalperiod> 
       <historicalperiod>6</historicalperiod> 
       <historicalperiod>8</historicalperiod> 
       </periods> 

以上XML可以有可變數量的節點。

我必須在以下格式此數據來場B複製:

   <periods> 
       <historicalperiod1>2</historicalperiod1> 
       <historicalperiod2>4</historicalperiod2> 
       <historicalperiod3>6</historicalperiod3> 
       <historicalperiod4>8</historicalperiod4> 
       </periods> 

我使用臨時表

   create table temp 
       (period int) 

       ;with cte as (
       select 
       T.C.value('.', 'nvarchar(max)') as period 
       from BatchQuotaSettings 
       CROSS APPLY HistoryPeriods.nodes('/periods/historicalperiod') as T(C)  
        ) 
       insert into temp (period) 
       select c.period 
        from cte c 

嘗試這是沒有更好的辦法來做到這一點?

回答

1

分解XML並使用row_number枚舉分解的節點。將您的新XML節點構建爲字符串,轉換爲XML並使用for xml path組合節點。

update T 
set B = (
     select cast('<historicalperiod'+cast(S.R as varchar(10))+'>'+S.V+'</historicalperiod'+cast(S.R as varchar(10))+'>' as xml) 
     from (
      select P.X.value('text()[1]', 'varchar(10)') as V, 
        row_number() over(order by P.X) as R 
      from T.A.nodes('/periods/historicalperiod') as P(X) 
      ) as S 
     for xml path(''), root('periods'), type 
     ) 
from BatchQuotaSettings as T 

SQL Fiddle

相關問題