来自oracle Table的gernerate XML文件格式

时间:2017-09-25 12:56:46

标签: sql xml oracle

我想要一个XML文件格式如下。

XML应如下所示: -

<server name="Server123">
<schema name="cwmm">
<table name="ACC" rows="1000000"/>
<table name="KEYS" rows="1000000"/>
</schema>
<schema name="CWM1610">
<table name="ACC" rows="1000000"/>
<table name="KEYS" rows="1000000"/>
</schema>

我所做的是创建一个名为TAB_INFO的临时表,其中包含有关table_owner,表及其​​行的信息。所以请帮助实现上述格式。我当时正在考虑使用dbms_xmlgen包,但我对如何实现上述目标一无所知。

表格包含以下列: -

owner
table_name
num_rows

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TAB_INFO (owner, table_name, num_rows ) AS
SELECT 'cwmm',    'ACC',  1000000 FROM DUAL UNION ALL
SELECT 'cwmm',    'KEYS', 1000000 FROM DUAL UNION ALL
SELECT 'CWM1610', 'ACC',  1000000 FROM DUAL UNION ALL
SELECT 'CWM1610', 'KEYS', 1000000 FROM DUAL;

查询1

SELECT XMLElement(
         "server",
         XMLAttributes( 'Server123' AS "name" ),
         XMLAGG( schema )
       ).getClobVal() AS xml
FROM   (
  SELECT XMLElement(
           "schema",
           XMLAttributes( owner AS "name" ),
           XMLAgg(
             XMLElement(
               "table",
               XMLAttributes(
                 table_name AS "name",
                 num_rows AS "rows"
               )
             )
           )
         ) AS schema
  FROM   tab_info
  GROUP BY owner
)

<强> Results

|                                                                                                                                                                                                                                                                   XML |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <server name="Server123"><schema name="CWM1610"><table name="ACC" rows="1000000"></table><table name="KEYS" rows="1000000"></table></schema><schema name="cwmm"><table name="ACC" rows="1000000"></table><table name="KEYS" rows="1000000"></table></schema></server> |