2011-02-11 129 views
2

我需要用兩個正確的值替換兩個XML節點,兩個郵政編碼。如何在SQL 2005中完成此操作。XML位於XML列中。如何替換XML節點值?

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

與IP22 2XH

問候

羅布

+0

都是同一條記錄中的節點,還是每個記錄列有一個郵政編碼節點? – RichardTheKiwi 2011-02-11 11:55:29

+0

在客戶節點內的郵編節點之前有2個節點。每個客戶有1個郵政編碼節點。 – user612970 2011-02-11 13:58:24

回答

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記錄多個郵政編碼節點 - 列,然後你可以使用下面的。 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