Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

sql server - XML DML for 2008 R2..How to modify nested Elements

      <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]       
    ')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...