I have an Oracle table with a xmltype column that stores XML in the following format
<?xml version="1.0" encoding="WINDOWS-1252"?>
<View>
<ReportValues>
<SalaryValue variable="HR" value="999"/>
<SalaryValue variable="floor" value="20"/>
</ReportValues>
</View>
I would like to know how to update the value from 999 to 666 for variable "HR" and also the variable value from "floor" to "SALES"
While the answer of @Анатолий Предеин is definitely correct for 10g and 11g one needs to be aware that updatexml
has been deprecated in Oracle 12c.
Since 12cR1 the recommended way to manipulate XML is XQuery Update Facility. It's not specific for Oracle but a W3C Recommendation implemented many other XML tools too.
Below you'll find a complete example. However I don't go into the details of XQuery but instead point you to the following documentation:
Example Setup
create table so61_t(
id number
,xml xmltype
);
insert into so61_t values(1, '<?xml version="1.0" encoding="WINDOWS-1252"?>
<View>
<ReportValues>
<SalaryValue variable="HR" value="999"/>
<SalaryValue variable="floor" value="20"/>
</ReportValues>
</View>');
insert into so61_t values(2, '<?xml version="1.0" encoding="WINDOWS-1252"?>
<View>
<ReportValues>
<SalaryValue variable="HR" value="998"/>
<SalaryValue variable="floor" value="19"/>
</ReportValues>
</View>');
Modify XML
update so61_t set xml =
xmlquery(
'copy $t := $x modify(
(for $i in $t/View/ReportValues/SalaryValue[@variable="HR"]/@value
return replace value of node $i with ''666'')
,(for $i in $t/View/ReportValues/SalaryValue[@variable="floor"]/@value
return replace value of node $i with ''SALES'')
) return $t'
passing xml as "x" returning content
)
where id = 1
;
Results
SQL> col id for 99
SQL> col xml for a78
SQL> select id, xmlserialize(content xml as varchar2(200)) as xml from so61_t;
ID XML
--- -------------------------------------------------
1 <?xml version="1.0" encoding="UTF-8"?>
<View>
<ReportValues>
<SalaryValue variable="HR" value="666"/>
<SalaryValue variable="floor" value="SALES"/>
</ReportValues>
</View>
2 <?xml version="1.0" encoding="UTF-8"?>
<View>
<ReportValues>
<SalaryValue variable="HR" value="998"/>
<SalaryValue variable="floor" value="19"/>
</ReportValues>
</View>
SQL>