XML DML для 2008 R2.. Как изменить вложенные элементы

      <Component>
          <Caption>2 7/8" x 1",Drill Collar,2 3/8 PAC</Caption>
          <Description>2 7/8" x 1",Drill Collar,2 3/8 PAC</Description>
          <Count>1</Count>
          <Sections>
            <Section>
              <Material>Steel AISI 4145</Material>
              <Connection>2 3/8 PAC</Connection>
              <Weight>28.7197</Weight>
              <Length>0.508</Length>
            </Section>
            <Section>
              <Material>Steel AISI 4145</Material>
              <Connection>NC50</Connection>
              <Weight>28.7197</Weight>
              <Length>0.508</Length>
            </Section>
            <Section>
              <Material>Steel AISI 4145</Material>
              <Connection>NC36</Connection>
              <Weight>28.7197</Weight>
              <Length>0.508</Length>
            </Section>
          </Sections>
        </Component>

У меня есть таблица компонентов в SQLServer 2008 R2, которая имеет поле идентификатора PK и другой столбец типа XML. В этом столбце XML у меня есть XML, который выглядит так, как вы видите выше. Для каждой строки я хочу изменить все вложенные блоки Section, чтобы у каждого из них было два дополнительных элемента. Это то, что я пробовал, и он только вставляет новые элементы в первый блок Section... но не два других.

DECLARE @MaxFeatures XML

 SET @MaxFeatures = N'<MaxAllowableTorque>0</MaxAllowableTorque>
            <MaxAllowableForce>0</MaxAllowableForce>'   

 Update Component   

    SET XMLDetails.modify('       
    insert sql:variable("@MaxFeatures")           
    after (/Component/Sections/Section/Length)[1]       
    ')

1 ответ

Решение

Вы можете вставить только в одно место в XML за один раз, поэтому вам нужно сделать это в цикле.

Обновляйте узлы по одному за раз и выходите из цикла, когда обновления не производятся.

declare @MaxFeatures xml

set @MaxFeatures = N'<MaxAllowableTorque>0</MaxAllowableTorque>
                     <MaxAllowableForce>0</MaxAllowableForce>'   

declare @I int 
set @I = 1

while 1 = 1
begin
  update Component
  set XMLDetails.modify('       
      insert sql:variable("@MaxFeatures")           
      after ((/Component/Sections/Section/Length)[sql:variable("@I")])[1]')
  where XMLDetails.exist('(/Component/Sections/Section/Length)[sql:variable("@I")]') = 1

  if @@rowcount = 0
    break

  set @I = @I + 1
end
Другие вопросы по тегам