如何读取包含XML的字段Oracle

时间:2015-06-08 21:46:54

标签: sql xml oracle xml-parsing type-conversion

生产环境中存在一个表格,其结构如下:

 CREATE TABLE gold_dwh_reload (
  msisdn              NUMBER(13,0)   NOT NULL,
  recharge_date       TIMESTAMP(6)   NOT NULL,
  impacted_balances   VARCHAR2(4000) NULL,
  lc_state            VARCHAR2(5)    NOT NULL)
  TABLESPACE sopfun_tab
  NOCOMPRESS
/

正常的咨询将以下结果为例:

MSISDN  RECHARGE_DATE   IMPACTED_BALANCES   LC_STATE
584124723950    29.04.15 13:23:38.000   <balance><name>B_LPP_Bs_Main</name><label></label><before>697.21429</before><after>797.21429</after><amount>100</amount><start></start><end></end><unit>Bs</unit></balance><balance><name>B_LPP_KB_National</name><label>PA_Adjustment</label><before>0</before><after>10240</after><amount>10240</amount><start>29042015000000</start><end>29052015000000</end><unit>Kbytes</unit></balance><balance><name>B_LSP_Bs_Promotions</name><label>PA_Adjustment</label><before>0</before><after>25</after><amount>25</amount><start>29042015000000</start><end>29052015000000</end><unit>Bs</unit></balance> ACT

但我需要打破列中的IMPACTED_BALANCES字段。谁知道我是怎么做到的?

1 个答案:

答案 0 :(得分:2)

这通常使用XMLTable

完成
select
    msisdn, recharge_date,
    x_name, x_label, x_before, x_after, x_amount,
    to_date(x_start, 'DDMMYYYYHH24MISS') x_start,
    to_date(x_end, 'DDMMYYYYHH24MISS') x_end,
    x_unit,
    lc_state
from gold_dwh_reload
cross join
xmltable('/balances/balance'
    passing xmltype('<balances>'||impacted_balances||'</balances>')
    columns
        x_name path '/balance/name',
        x_label path '/balance/label',
        x_before number path '/balance/before',
        x_after number path '/balance/after',
        x_amount number path '/balance/amount',
        x_start path '/balance/start',
        x_end path '/balance/end',
        x_unit path '/balance/unit'
);

这是SQL Fiddle

混合SQL和XML功能强大但会产生许多潜在的类型安全问题。单个无效的日期,数字或XML文件将使整个查询崩溃。示例中的字符串不是有效的XML,这就是我将另一个标记连接到开头和结尾的原因。