且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Oracle PL/SQL 中解析一个简单的 XML 片段并将其加载到全局临时表中?

更新时间:2022-12-04 07:45:46

坦率地说,Oracle 的 XML DB 实现有许多令人眼花缭乱的选项,而且并不总是清楚(至少对我而言)哪个选项适用于任何给定的场景.在这种特殊情况下,您想要的是 XMLTable(),它将 XQuery 转换为一组行.

Oracle's XML DB implementation has a frankly bewildering number of options, and it is not always clear (at least to me) which one applies in any given scenario. In this particular case the one you want is XMLTable(), which turns an XQuery into a set of rows.

首先我们创建一个表.

SQL> create table t23
  2      (field01 number
  3       , field02 number
  4       , field03 char(1)
  5       )
  6  /

Table created.

SQL>

然后我们填充它...

SQL> declare
  2      x varchar2(2000) := '<ArrayOfRecords>
  3                        <Record Field01="130" Field02="1700" Field03="C" />
  4                        <Record Field01="131" Field02="1701" Field03="C" />
  5                        <Record Field01="132" Field02="1702" Field03="C" />
  6                   </ArrayOfRecords>';
  7  begin
  8      insert into t23
  9      select *
 10      from xmltable
 11          ( '/ArrayOfRecords/Record'
 12             passing xmltype (x)
 13             columns f1 number path '@Field01'
 14                     , f2 number path '@Field02'
 15                     , f3 char(1) path '@Field03'
 16          )
 17      ;
 18  end;
 19  /

PL/SQL procedure successfully completed.

SQL>

最后我们证明它有效......

Finally we prove it worked....

SQL> select * from t23
  2  /

   FIELD01    FIELD02 F
---------- ---------- -
       130       1700 C
       131       1701 C
       132       1702 C

SQL>