重要事项:必须在路径的末尾指定 text()。这一步确保即使是空元素(即不具有现有文本节点的元素)也进行更新。如果省略了 text() 且不存在要替换的现有文本值,更新命令就会失败。
使用 XMLUpdate 追加子节点。
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://posample.org">
<update action="append" col="1" path="/x:customerinfo/x:addr">
<county>Santa Clara</county>
</update>
</updates>',
'Select info from XMLCustomer where cid=1006',
'update XMLCustomer set info=? where cid=1006',?,?);
|
注意:新节点 不在任何名称空间中。
使用 XMLUpdate 将更新的 XML 插入新行。
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://posample.org">
<update action="replace" col="1"
path="/x:customerinfo/x:name">
<name>Marja Soininen</name>
</update>
<update action="replace" col="1"
path="/x:customerinfo/@Cid">1008</update>
</updates>',
'Select info from XMLCustomer where cid=1006',
'insert into XMLCustomer (cid, info ) values (1008, cast( ? as xml))',?,?);
|
使用 XMLUpdate 删除节点。
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://posample.org">
<update action="delete" col="1" path="/x:customerinfo/x:name"/>
</updates>',
'Select info from XMLCustomer where cid=1006',
'update XMLCustomer set info=? where cid=1006',?,?);
|
当更新元素中没有设置 @action 时,就默认执行替换操作。
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://posample.org">
<update col="1" path="//x:customerinfo[@Cid=1006]/x:phone">
<phone><areacode>910</areacode></phone>
</update>
</updates>',
'Select info from XMLCustomer where cid=1006',
'update XMLCustomer set info=? where cid=1006',?,?);
|
以下示例展示带有无效名称空间或带有没有前缀的名称空间的 XMLUpdate:
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://my.org">
<update col="1"
path="//x:customerinfo[@Cid=1006]/x:phone">
<phone><areacode>910</areacode></phone>
</update>
</updates>',
'Select info from XMLCustomer where cid=1006',
'update XMLCustomer set info=? where cid=1006',?,?);
|
该查询返回设置为 1 的错误,以及如下错误消息:
<error type='abort' action='replace' msg='Cannot find path
//x:customerinfo[@Cid=1006]/x:phone) in the XMLDocument'>
|
以下示例展示的 XMLUpdate 在更新元素中有一个遗漏的路径:
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates > <update col="1"> (20+?)*32-? </update></updates>',
'Select info from XMLCustomer where cid=1006',
'update XMLCustomer set info=? where cid=1006',?,?);
|
该查询返回设置为 1 的错误,以及如下错误消息:
<error type='abort' action='null' msg='path not defined'></error>
|
使用相同名称空间中的新节点替换某个节点。
Call DB2XMLFUNCTIONS.XMLUPDATE (
'<updates namespaces="x:http://posample.org">
<update action="replace" col="1" path="/x:customerinfo/x:name">
<name xmlns="http://posample.org">
<fname>Marja</fname><lname>Soininen</lname>
</name>
</update>
</updates>',
'Select info from XMLCustomer where cid=1008',
'insert into XMLCustomer (cid, info ) values (1007, cast( ? as xml))',?,?);
|
结束语
本文描述的更新存储过程允许对本机存储在数据库中的 XML 文档进行部分更新。下一篇文章将深度挖掘和具体研究新的 XML 支持对迁移现有基于 XML 的应用程序的重大意义。
致谢
感谢 Matthias Nicola、Bert Van der Linden、Irina Kogan、Annie Wang、Ying Chen 和 Xiaoli Du 在撰写这篇文章时给予的帮助。
(编辑:aniston)
|