[英]How can I insert multiple xml nodes with XMLQuery (XQuery) in Oracle SQL?
我创建了以下测试案例来演示我的问题:
create table test_table (idx number, a varchar2(20), b varchar2(20));
insert into test_table values (1, 'item1', 'value1');
insert into test_table values (2, 'item2', 'value2');
select appendChildXML(
xmltype('<inventory></inventory>'),
'/inventory',
xmlagg(
xmlelement("id", xmlattributes(tt.idx as "val"),
xmlelement("listing",
xmlelement("item",tt.a),
xmlelement("value",tt.b)
)))) as xml
from test_table tt
;
这给出了所需的输出:
<inventory>
<id val="1">
<listing>
<item>item1</item>
<value>value1</value>
</listing>
</id>
<id val="2">
<listing>
<item>item2</item>
<value>value2</value>
</listing>
</id>
</inventory>
但是,如果尝试使用XMLQuery,则会出现错误。
select XMLQuery(
(
'copy $tmp := . modify insert node '
|| xmlagg(
xmlelement("id", xmlattributes(tt.idx as "val"),
xmlelement("listing",
xmlelement("item",tt.a),
xmlelement("value",tt.b)
)))
|| ' as last into $tmp/inventory return $tmp'
)
PASSING xmltype('<inventory></inventory>') RETURNING CONTENT
) as xml
from test_table tt
;
错误:
ORA-19112: error raised during evaluation:
XVM-01003: [XPST0003] Syntax error at 'id'
1 copy $tmp := . modify insert node <id val="1"><listing><item>item1</item><v
- ^
19112. 00000 - "error raised during evaluation: %s"
*Cause: The error function was called during evaluation of the XQuery expression.
*Action: Check the detailed error message for the possible causes.
我认为问题与以下事实有关:我插入多个id节点,因为如果表中只有一个ID节点将起作用,但是我不明白为什么appendChildXML可以工作而XMLQuery不能工作。
我猜测也许我需要使用FLWOR表达式,但是我无法创建一个有效的表达式。
我当前正在使用Oracle 11g,并将迁移到12c(由于在12c中不推荐使用appendChildXML,因此尝试迁移到XMLQuery)。 我几乎没有在Oracle中使用XML的经验,也没有以前的XMLQuery经验。
谁能提供有关如何使XMLQuery工作的建议? 谢谢!
您可以使用ora:view函数查询表,然后使用FLWOR表达式生成XML,如下所示:
10/12/2015 19:53:25:SQL> SELECT XMLQuery('<inventory>
2 {for $i in ora:view("TEST_TABLE")
3 let $idval := $i/ROW/IDX,
4 $item := $i/ROW/A/text(),
5 $value := $i/ROW/B/text()
6 return <id val="{$idval}">
7 <listing>
8 <item>{$item}</item>
9 <value>{$value}</value>
10 </listing>
11 </id>}
12 </inventory>'
13 RETURNING CONTENT) AS test_xml
14 FROM DUAL;
TEST_XML
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<inventory><id val="1"><listing><item>item1</item><value>value1</value></listing></id><id val="2"><listing><item>item2</item><value>value2</value></listing></id></inventory>
我可以通过下面的查询获得所需的结果。 感谢Francisco Sitja的回答和FLWOR的表达,这引导了我走向完整的答案。
select XMLQuery(
(
'copy $tmp := . modify insert node '
|| 'for $i in ora:view("TEST_TABLE")
let $idval := $i/ROW/IDX,
$item := $i/ROW/A/text(),
$value := $i/ROW/B/text()
return <id val="{$idval}">
<listing>
<item>{$item}</item>
<value>{$value}</value>
</listing>
</id>'
|| ' as last into $tmp/inventory return $tmp'
)
PASSING xmltype('<inventory></inventory>') RETURNING CONTENT
) as xml
from dual;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.