1
      <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 ID フィールドと XML 型の別の列を持つコンポーネント テーブルがあります。その XML 列には、上記のような XML があります。行ごとに、ネストされたすべての Section ブロックを変更して、それぞれに 2 つの要素を追加したいと考えています。これは私が試したもので、新しい要素を最初の Section ブロックに挿入するだけです...他の2つには挿入しません。

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]       
    ')
4

1 に答える 1

1

一度に挿入できるのは XML の 1 か所だけなので、ループで実行する必要があります。

一度に 1 つずつノードを更新し、更新が行われなかった時点でループを終了します。

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
于 2013-03-28T12:52:40.247 に答える