从游标中获取XMLType

时间:2015-12-08 09:21:10

标签: oracle plsql

任何人都知道我是否可以从游标生成XMLType而无需手动指定每一行的名称?

我希望能够遍历我的查询,并为每一行获取单独的XML。

我无法使用DBMS_XMLGEN.getXMLType获得解决方案,但也许我没有正确使用它。

CREATE OR REPLACE PROCEDURE "MY_SCHEMA"."TEST" AS

CURSOR mySelectCursor is
    SELECT '1a' as "column1", '1b' as "column2" FROM DUAL
    UNION ALL
    SELECT '2a' as "column1", '2b' as "column2" FROM DUAL;

myXMLType XMLType;
BEGIN

FOR mySelect in mySelectCursor
    LOOP
        -- I would like to replace the following line of code
        myXMLType := XMLType('<row><column1>' || mySelect."column1" || '</column1><column2>' || mySelect."column2" || '</column2></row>');
        -- by something similar to this (not working) one
        --myXMLType := mySelect.getXMLType();
        dbms_output.put_line(myXMLType.getClobVal());
    END LOOP;
END;

--The following code outputs
--<row><column1>1a</column1><column2>1b</column2></row>
--<row><column1>2a</column1><column2>2b</column2></row>

4 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。

感谢您的帮助。

CREATE OR REPLACE PROCEDURE "MY_SCHEMA"."TEST" AS

CURSOR mySelectCursor is
    SELECT 
        VALUE(table_temp) as "XMLTYPE"
    FROM 
        table(
            XMLSequence(
                Cursor(
                    SELECT '1a' as "column1", '1b' as "column2" FROM DUAL
                    UNION ALL
                    SELECT '2a' as "column1", '2b' as "column2" FROM DUAL
                )
            )
        ) table_temp;

BEGIN

FOR mySelect in mySelectCursor
    LOOP
        dbms_output.put_line('===');
        dbms_output.put_line(mySelect."XMLTYPE".getClobVal());
    END LOOP;
END;


-- Output is :

--===
-- <ROW>
--  <column1>1a</column1>
--  <column2>1b</column2>
-- </ROW>
--
--===
-- <ROW>
--  <column1>2a</column1>
--  <column2>2b</column2>
-- </ROW>

答案 1 :(得分:0)

以下是代码段,您需要使用DBMS_XMLGEN.getxml:

CELLTYPE_STRING

这是在游标中循环的代码片段

DECLARE
  v_xml   CLOB;
  v_more  BOOLEAN := TRUE;
BEGIN
  v_xml := DBMS_XMLGEN.getxml('select * from dual');
  dbms_output.put_line(v_xml);
END;
/

答案 2 :(得分:0)

此查询是否符合您的需要:

WITH t AS
    (SELECT '1a' AS c1, '1b' AS c2 FROM DUAL
    UNION ALL
    SELECT '2a' AS c1, '2b' AS c2 FROM DUAL)
SELECT XMLELEMENT("row", 
           XMLELEMENT("column1", c1 ), 
           XMLELEMENT("column2", c2 )
       ) AS myXMLType
FROM t;

另一种方式是这个:

CREATE OR REPLACE TYPE "row" AS OBJECT (
 "column1" VARCHAR2(100),
 "column2" VARCHAR2(100))
/

WITH t AS
    (SELECT '1a' AS c1, '1b' AS c2 FROM DUAL
    UNION ALL
    SELECT '2a' AS c1, '2b' AS c2 FROM DUAL)
SELECT XMLTYPE("row"(c1,c2)) AS myXMLType
FROM t;

答案 3 :(得分:0)

以下是使用XMLTABLE而不是XMLSEQUENCE的解决方案。

<script rel="nofollow" type="text/javascript">
    //<![CDATA[