使用Oracle PL/SQL XMLQUERY和XQuery而不是“EXTRACT(XML)”的优点是什么

1rhkuytd  于 2023-06-22  发布在  Oracle
关注(0)|答案(1)|浏览(125)

我注意到Oracle EXTRACT(XML)函数在Oracle 11g中已被弃用。
我曾经使用以下方法进行XML处理:

DECLARE
  TYPE xmltype_table IS TABLE OF xmltype INDEX BY PLS_INTEGER;
  vt_xml_tab xmltype_table;
  v_xml      xmltype;
BEGIN
  --Generate simple XML document to pretend we received it by some interface
  SELECT xmltype(dbms_xmlgen.getxml('select level, dbms_random.random rnd from dual connect by level<1000')) INTO v_xml FROM dual;

  --Get nodes
  SELECT VALUE(xm) xmlt BULK COLLECT INTO vt_xml_tab FROM TABLE(xmlsequence(v_xml.extract('/ROWSET/ROW/LEVEL'))) xm;

  --Do whatever processing I like
  FOR i IN 1..vt_xml_tab.count LOOP
    dbms_output.put_line(vt_xml_tab(i).extract('LEVEL/text()').getstringval());
  END LOOP;
END;
/

由于EXTRACT已被弃用,Oracle建议我使用XMLQUERY:http://docs.oracle.com/cd/E18283_01/server.112/e17118/functions060.htm
我想重写我以前的处理如下:

DECLARE
  TYPE xmltype_table IS TABLE OF xmltype INDEX BY PLS_INTEGER;
  vt_xml_tab xmltype_table;
  v_xml      xmltype;
BEGIN
  --Generate simple XML document to pretend we received it by some interface
  SELECT xmltype(dbms_xmlgen.getxml('select level, dbms_random.random rnd from dual connect by level<1000'))
    INTO v_xml
    FROM dual;

  SELECT xmlquery('for $i in /ROWSET/ROW
      return $i/LEVEL' passing rowset_xml RETURNING content)
    INTO v_xml
    FROM (SELECT v_xml rowset_xml FROM dual);

  --Get nodes
  SELECT VALUE(xm) xmlt BULK COLLECT INTO vt_xml_tab FROM TABLE(xmlsequence(v_xml)) xm;

  --Do whatever processing I like
  FOR i IN 1 .. vt_xml_tab.count LOOP
    FOR x IN (SELECT extractvalue(vt_xml_tab(i), 'LEVEL') lvl FROM dual) LOOP
      dbms_output.put_line(x.lvl);
    END LOOP;
  END LOOP;
END;
/

但事实证明,使用XMLQUERY要慢得多(在我的机器上,用挂钟测量是0.8秒对1.8秒)。
有没有更好的方法不使用EXTRACT函数?

ki1q1bka

ki1q1bka1#

BEGIN
    FOR rec IN (
        SELECT 
        t.lvl, t.rnd
        FROM  
        XMLTABLE(
            '/ROWSET/ROW' PASSING (
            SELECT XMLTYPE(DBMS_XMLGEN.GETXML('select level, dbms_random.random rnd from dual connect by level<1000'))
                FROM Dual
            )
            COLUMNS 
                lvl NUMBER path 'LEVEL',
                rnd NUMBER path 'RND'
        ) t
    )
    LOOP
        DBMS_OUTPUT.PUT_LINE(rec.lvl || ' ' || rec.rnd);
    END LOOP ;
END ;
/

相关问题