XML DML for 2008 R2..How to modify nested Elements

て烟熏妆下的殇ゞ 提交于 2019-11-28 10:40:05

问题


      <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>

I have a Component table in SQLServer 2008 R2 that has a PK ID field and another column of type XML. In that XML column I have XML that looks like what you see above. For each row, I want to modify all of the nested Section blocks so they each have two additional Elements. This is what I've tried and it only inserts the new elements into the first Section block...but not the other two.

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:


You can only insert into one place in the XML at a time so you need to do it in a loop.

Update the nodes one at at time and exit the loop when there where no updates made.

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


来源:https://stackoverflow.com/questions/15681995/xml-dml-for-2008-r2-how-to-modify-nested-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!