如何让XMLForest返回表的所有列

时间:2017-10-03 08:11:29

标签: sql oracle

我有一个包含大量列的表格(例如:Column1,Column 2,Column 3,Column 4,...)

我想使用XMLElement和XMLForest函数生成XML,每列都是一个标记。

我只能通过手动添加XMLForest中的每一列来完成此操作: 例如:

SELECT
XMLElement("ParentTag", 
    XMLForest(TABLE.Column1, 
              TABLE.Column2,
              TABLE.Column2,
              ...)
)
FROM ...

结果:

<ParentTag> <Column1>Value1</Column1> <Column2>Value2</Column2> ...</ParentTag>

但是我想避免键入每一栏,因为将来他们的人数可能会增加。

我该怎么做这样的事情? :

SELECT
XMLElement("ParentTag", 
    XMLForest(TABLE.*)
)
FROM ...

2 个答案:

答案 0 :(得分:1)

  

我该怎么做这样的事情? :

SELECT
XMLElement("ParentTag", 
    XMLForest(TABLE.*)
)
FROM ...

您不能,您必须单独输入所有名称。

您可以使用动态SQL生成查询

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name (
  id NUMBER,
  a  NUMBER,
  b  NUMBER,
  c  NUMBER,
  d  NUMBER
);

查询1

SELECT '
SELECT XMLElement(
         "ParentTag", 
         XMLForest( '
         || LISTAGG( '"' || column_name || '"', ',' )
              WITHIN GROUP ( ORDER BY Column_id )
         ||' ) ) FROM ...' AS query
FROM   user_tab_columns
WHERE  table_name = 'TABLE_NAME'

<强> Results

|                                                 QUERY |
|-------------------------------------------------------|
| SELECT XMLElement(                                    |
|          "ParentTag",                                 |
|          XMLForest( "ID","A","B","C","D" ) ) FROM ... |

答案 1 :(得分:1)

您可以使用PLSQL程序来完成您的要求。在PLSQL过程中,它会接受Tablename,然后生成XMLForest并显示结果。见下文:

-- Creating a type of XMLTYPE
CREATE OR REPLACE TYPE Outpt IS TABLE OF XMLTYPE;
/

--Procedure with In parameter as Tablename and out parameter as resultset
CREATE OR REPLACE PROCEDURE XM_FOREST (tabnm VARCHAR2, v_out IN OUT Outpt)
AS
   var     VARCHAR2 (4000);
   v_sql   VARCHAR2 (4000);
BEGIN
   FOR i IN (SELECT cname
               FROM col
              WHERE tname = tabnm)
   LOOP
      var := var || ',' || i.cname;
   END LOOP;

   var := LTRIM (var, ',');

   v_sql :=
         'select XMLElement("ParentTag",XMLForest('
      || var
      || '  ) ) from  '
      || tabnm;

   EXECUTE IMMEDIATE v_sql BULK COLLECT INTO v_out;
END;

--------------

--Execution
DECLARE
   var_out   Outpt := Outpt ();
   LCLOB     CLOB;
BEGIN
   var_out.EXTEND;
   XM_FOREST (tabnm => 'EMPLOYEE', v_out => var_out);

   FOR i IN 1 .. var_out.COUNT
   LOOP
      LCLOB := var_out (i).getCLOBVAL ();
      DBMS_OUTPUT.put_line (LCLOB);
   END LOOP;
END;
------
--Result

 SQL> /
    <ParentTag><EMPLOYEE_ID>1</EMPLOYEE_ID><FIRST_NAME>XXX</FIRST_NAME></ParentTag>
    <ParentTag><EMPLOYEE_ID>2</EMPLOYEE_ID><FIRST_NAME>YYY</FIRST_NAME></ParentTag>

 PL/SQL procedure successfully completed.