XML输出表的值

时间:2019-01-30 16:21:49

标签: sql xml oracle plsql

我必须在代码中进行哪些更改才能获得这样的输出?

<Team Name="x">
  <Nationality nationality="a">
   <Player name="abc"/>  
   <Player name="def"/>  
  </Nationality>

  <Nationality nationality="b">
   <Player name="xyz"/>  
  </Nationality>
</Team>

此刻,我有以下代码:

SELECT XMLElement("Team", XMLATTRIBUTES(TeamName as "Name"),
(SELECT XMLElement("Nationality", XMLAttributes(nationality AS "Nationality"), 
        XMLAgg(XMLElement("Player", name)))
FROM players
WHERE team_id = 03111 
GROUP BY nationality 
))
from teams

“中间选择”返回我想要的结果,但是需要很多行。 我希望所有内容都在同一行中,我想如果我将“常规” XMLElement放入,它将起作用,但是会返回此错误:

  
      
  1. 00000-“单行子查询返回多个行”
  2.   

我该如何解决?

PS:我有两个桌子,玩家和团队。国籍不是桌子,而是玩家的属性

1 个答案:

答案 0 :(得分:0)

嵌套您的XMLAGG和XMLELEMENT调用,例如(用于EMP表)

SELECT XMLSERIALIZE (
          CONTENT
          XMLELEMENT (
             "Department",
                XMLAGG (
                   XMLELEMENT (
                      "Job",
                       XMLATTRIBUTES (job AS "Job"),
                       XMLAGG (
                          XMLELEMENT (
                             "Employee",
                              XMLATTRIBUTES (ename AS "Name"))))))
          AS CLOB INDENT SIZE = 3) xml
FROM   emp e INNER JOIN dept d ON (d.deptno = e.deptno)
WHERE  d.dname = 'SALES'
GROUP BY e.job;

返回。...

<Department>
   <Job Job="CLERK">
      <Employee Name="JAMES"/>
   </Job>
   <Job Job="MANAGER">
      <Employee Name="BLAKE"/>
   </Job>
   <Job Job="SALESMAN">
      <Employee Name="WARD"/>
      <Employee Name="ALLEN"/>
      <Employee Name="TURNER"/>
      <Employee Name="MARTIN"/>
   </Job>
</Department>