4

我有以下 xml 字段,我需要在其中替换其中一个节点的值:

<DataFormItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="bb_appfx_dataforms">
  <Values>
    <fv ID="FUNDRAISERID">
      <Value xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">1009fb5a-41a0-40c1-8685-d5973fb71df7</Value>
      <ValueTranslation>John Smith</ValueTranslation>
    </fv>
    <fv ID="STARTDATE">
      <Value xsi:type="xsd:dateTime">2015-01-01T00:00:00</Value>
    </fv>
  </Values>
</DataFormItem>

我需要将 STARTDATE 值“2015-01-01T00:00:00”更改为“2016-01-01T00:00:00”。为此,我编写了以下查询:

update KPIINSTANCE
SET     NAME = '2016 ' + SUBSTRING(k.name, 6,150), 
        PARAMETERSXML.modify('
        declare namespace df = "bb_appfx_dataforms";
        replace value of (/df:DataFormItem/df:Values/df:STARTDATE/df:Value)[1] with "2016-01-01T00:00:00" cast as xs:dateTime ?')
FROM KPIINSTANCE K
        JOIN KPICATALOG KP ON KP.ID = K.KPICATALOGID
where k.ID = '43C6DA6B-420A-4D4E-BA31-84C8054B4AB6'

据我所知,这是正确的,但是当我尝试运行查询时,出现错误:XQuery [KPIINSTANCE.PARAMETERSXML.modify()]: The target of 'replace value of' must be a non-metadata属性或具有简单类型内容的元素,找到 'element(df{bb_appfx_dataforms}:Value,xdt:untyped) ?'

由于这个节点是输入的,我不确定为什么错误说它没有输入。有人有想法么?

4

1 回答 1

5

您的 XPath 错误... STARTDATE 不是节点名称,而是“fv”下方的属性名称

我认为这更容易解决:有问题的节点甚至没有命名空间前缀。试试这样:

PARAMETERSXML.modify('replace value of (/DataFormItem/Values/fv[@ID="STARTDATE"]/Value/text())[1] with "2016-01-01T00:00:00"')

我是这样测试的:

DECLARE @KPIINSTANCE TABLE(ID UNIQUEIDENTIFIER, NAME VARCHAR(100),PARAMETERSXML XML);
INSERT INTO @KPIINSTANCE VALUES
('43C6DA6B-420A-4D4E-BA31-84C8054B4AB6'
,'test'
,'<DataFormItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="bb_appfx_dataforms">
  <Values>
    <fv ID="FUNDRAISERID">
      <Value xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">1009fb5a-41a0-40c1-8685-d5973fb71df7</Value>
      <ValueTranslation>John Smith</ValueTranslation>
    </fv>
    <fv ID="STARTDATE">
      <Value xsi:type="xsd:dateTime">2015-01-01T00:00:00</Value>
    </fv>
  </Values>
</DataFormItem>'
);

SELECT * FROM @KPIINSTANCE;


UPDATE @KPIINSTANCE
SET     NAME = '2016 ' + 'test', 
        PARAMETERSXML.modify('replace value of (/DataFormItem/Values/fv[@ID="STARTDATE"]/Value/text())[1] with "2016-01-01T00:00:00"')
FROM @KPIINSTANCE K
        --JOIN KPICATALOG KP ON KP.ID = K.KPICATALOGID
WHERE K.ID = '43C6DA6B-420A-4D4E-BA31-84C8054B4AB6'

SELECT * FROM @KPIINSTANCE;
于 2016-01-18T10:52:26.657 回答