更新多个节点的XML数据

时间:2019-03-30 14:19:48

标签: sql-server xml sql-server-2008

我要根据所选计划更新Isselected计划数据

<Plans>
        <Plan>
          <Details>
               <IsSelected>true</IsSelected>
         </Details>  
        </plan> 
        <Plan>
          <Details>
                 <IsSelected>false</IsSelected>
         </Details>  
        </plan> 
        <Plan>
          <Details>
                <IsSelected>false</IsSelected>
         </Details>  
        </plan>
  </Plans>


if((SELECT count(Col.value('(Details)[1]', 'nvarchar(max)')) AS Selected FROM @DataXml.nodes('Options/Option') AS Tbl(Col)) > 1)
                                BEGIN                   

                                    SET @DataXml.modify(' replace value of (/*/Options/Option[sql:variable("@OptionID")]/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                                END
                            ELSE
                            BEGIN                            

                                    SET @DataXml.modify(' replace value of (/*/Options/Option/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                            END

,但是上面的查询总是更新第一个查询。

('string',
([array],
{'string',
'string'}))

如果我可以像上面的数据那样获得节点计数,它应该返回计数3,我可以设法解决这个问题。

1 个答案:

答案 0 :(得分:0)

这个答案可能很晚了...但是可能仍然有用...

我必须承认,我不完全了解您的问题。试试看:

一个 mockup-XML

DECLARE @xml XML=
N'<Plans>
        <Plan>
          <Details>
               <IsSelected>true</IsSelected>
         </Details>  
        </Plan> 
        <Plan>
          <Details>
                 <IsSelected>false</IsSelected>
         </Details>  
        </Plan> 
        <Plan>
          <Details>
                <IsSelected>false</IsSelected>
         </Details>  
        </Plan>
  </Plans>';

-此查询将回答您的问题

  

如果我能像上述数据那样获得节点数,它应该返回计数3,我可以设法解决这个问题

SELECT @xml.value('count(/Plans/Plan)','int') AS CountOfPlans;

-并且此查询会将第二个<IsSelected>更改为新值

DECLARE @position INT=2;
DECLARE @newValue VARCHAR(100)='blah';

SET @xml.modify('replace value of (/Plans/Plan[sql:variable("@position")]/Details/IsSelected/text())[1] with sql:variable("@newValue")');

SELECT @xml;

第一个返回“ 3”,第二个返回此XML

<Plans>
  <Plan>
    <Details>
      <IsSelected>true</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>blah</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>false</IsSelected>
    </Details>
  </Plan>
</Plans>