【问题标题】:how to create XML tree when sql query return multiple rowssql查询返回多行时如何创建XML树
【发布时间】:2017-03-31 11:42:33
【问题描述】:

我有一个表(tab1),它加入了 2 个名为 tab2 的表,它可以返回多行。我也加入 tab3,它只返回唯一的行

SELECT col1,col2,col3
FROM tab1 
LEFT JOIN tab2 ON tab1.col1=tab2.col2 
LEFT JOIN tab3 ON tab1.col1=tab3.col1

我需要 XML 格式的结果

<JOB>
<col1>1<col1>
<tab2>
<col2>1<\col2>
<col3>2<\col3>
<\tab2>
<tab2>
<col2>4<\col2>
<col3>5<\col3>
<\tab2>
<\JOB>

有什么办法可以在 sql 中做到这一点 如果您需要更多信息,请告诉我

【问题讨论】:

  • 不,我的问题是,当同一 xml 标记中有多个 tab2 行时,我想创建一个集合。检查从 tab2 到 \tab2。
  • 列是哪个表的一部分?标签内的数字代表什么?为什么没有提到tab3?你试过什么?为什么需要 XML?
  • select xmlelement("JOB", xmlforest(col1), xmlagg(xmlelement("TAB2", xmlforest(col2, col3)))) from tab1 left join tab2 on col1 = col2 left join tab3 on col1 = col3 group by col1;

标签: sql xml oracle oracle10g


【解决方案1】:

您可以通过 2 种方式生成 XML 文档。

1) 使用 XMLTYPE 的构造函数

DECLARE
   l_refcursor SYS_REFCURSOR;
   l_xmltype XMLTYPE;
BEGIN
   OPEN l_refcursor FOR SELECT employee_id
                             , first_name
                             , job_id
                          FROM employee 
                          join emplyee
                          on employee_id = empid;


   l_xmltype := XMLTYPE(l_refcursor);
   dbms_output.put_line(l_xmltype.getClobVal);
END;
/

2) 使用DBMS_XMLGEN 包。 DBMS_XMLGEN 内置类似于 XMLTYPE 构造函数,但直接接受查询:

DECLARE
   l_xmltype XMLTYPE;
BEGIN
    l_xmltype := dbms_xmlgen.getxmltype('SELECT employee_id
                                             , first_name
                                             , job_id
                                          FROM employee 
                                          join emplyee
                                          on employee_id = empid'
                                       );

    dbms_output.put_line(l_xmltype.getClobVal);
END;
/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多