如何替换XML节点值?

时间:2011-02-11 11:49:17

标签: sql-server xml

我需要替换2个XML节点,两个邮政编码都有正确的值。我如何在SQL 2005中完成此任务.XML位于XML列中。

<customer><postcode>P22 2XH</postcode></customer>

IP22 2XH

此致

罗布

1 个答案:

答案 0 :(得分:1)

更新表中的xml节点的工作示例

create table xml (xml xml);
insert xml values('<customer name="John"><postcode>P22 2XH</postcode></customer>');
insert xml values('<customer name="Doe"><postcode>P22 2XH</postcode></customer>');
insert xml values('<customer name="Jane"><postcode>P9 2XH</postcode></customer>');

UPDATE xml
SET xml.modify('
  replace value of (//customer/postcode[text()="P22 2XH"]/text())[1]
  with "IP22 2XH" ');

select * from xml;

如果您有多个邮政编码节点PER xml-record-column,那么您可以使用以下内容。 SQL Server每个modify只允许一个xml节点替换,所以你需要循环它。

create table xml (salesperson varchar(100), portfolios xml);
insert xml values('jim','
    <customer name="John"><postcode>P22 2XH</postcode></customer>
    <customer name="Doe"><postcode>P22 2XH</postcode></customer>
    <customer name="Jane"><postcode>P9 2XH</postcode></customer>');
insert xml values('mary','
    <customer name="Joe"><postcode>Other</postcode></customer>
    <customer name="Public"><postcode>P22 2XH</postcode></customer>');

while exists (
    select * from xml
    cross apply portfolios.nodes('//customer/postcode[text()="P22 2XH"]') n(c))
UPDATE xml
SET portfolios.modify('
  replace value of (//customer/postcode[text()="P22 2XH"]/text())[1]
  with "IP22 2XH" ');
;

select * from xml