【问题标题】:How to extract data in tabular format from XML field in Oracle database?如何从 Oracle 数据库中的 XML 字段中提取表格格式的数据?
【发布时间】:2015-03-02 23:38:56
【问题描述】:

我正在尝试从 Oracle 数据库中的 XML 字段中提取表格格式的数据。 请参阅下面的示例 xml 字段:

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <element1>
        <Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
        <element2>
            <element3 UnitPrice="3.2" ItemID="njh1"/>
            <element3 UnitPrice="4.1" ItemID="ole5"/>
            <element3 UnitPrice="4.6" ItemID="usd3"/>
            <element3 UnitPrice="8.2" ItemID="eor9"/>
            <element3 UnitPrice="2.9" ItemID="abc8"/>
            <element3 UnitPrice="5.1" ItemID="gfd3"/>
            <element3 UnitPrice="4.9" ItemID="kdu0"/>
            <element3 UnitPrice="6.1" ItemID="uso8"/>
        </element2>
    </element1>
</root>

我的目标是从上面的xml字段中查询itemID和UnitPrice字段,格式如下:

ItemID  UnitPrice
njh1      3.2
ole5      4.1
usd3      4.6
eor9      8.2
abc8      2.9
gfd3      5.1
kdu0      4.9
uso8      6.1

我对从 xml 字段查询数据还很陌生。我尝试过使用 getStringVal,但我得到的只是一个长字符串。 请就解决方案提出建议。请注意,我没有此数据库的 dba 权限。

谢谢

【问题讨论】:

  • 在最近的 Oracle 数据库版本中,您可以使用标准的 XMLTABLE() 函数。

标签: sql xml oracle extract


【解决方案1】:

您必须为此使用XMLTABLE 函数。

SQL Fiddle

Oracle 11g R2 架构设置:

create table xml_test(
  xml_col varchar2(2000)
  );

insert into xml_test values(
  '<?xml version=''1.0'' encoding=''UTF-8''?>
<root>
    <element1>
        <Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
        <element2>
            <element3 UnitPrice="3.2" ItemID="njh1"/>
            <element3 UnitPrice="4.1" ItemID="ole5"/>
            <element3 UnitPrice="4.6" ItemID="usd3"/>
            <element3 UnitPrice="8.2" ItemID="eor9"/>
            <element3 UnitPrice="2.9" ItemID="abc8"/>
            <element3 UnitPrice="5.1" ItemID="gfd3"/>
            <element3 UnitPrice="4.9" ItemID="kdu0"/>
            <element3 UnitPrice="6.1" ItemID="uso8"/>
        </element2>
    </element1>
</root>'
  );

查询:

select cols.ItemID, cols.UnitPrice
from xml_test x,
  xmltable('root/element1/element2/element3'
           passing xmltype(x.xml_col)
           columns ItemID varchar2(10) path '@ItemID',
                   UnitPrice varchar2(10) path '@UnitPrice'
           ) cols;

Results:

| ITEMID | UNITPRICE |
|--------|-----------|
|   njh1 |       3.2 |
|   ole5 |       4.1 |
|   usd3 |       4.6 |
|   eor9 |       8.2 |
|   abc8 |       2.9 |
|   gfd3 |       5.1 |
|   kdu0 |       4.9 |
|   uso8 |       6.1 |

【讨论】:

  • 感谢您的反馈。我没有权限在这个数据库上运行 CREATE 语句。鉴于此限制,有没有办法提取类似的结果?谢谢
  • 那个创建表只是为了演示。您应该对您的表运行 select 语句。
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2012-11-11
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
相关资源
最近更新 更多