通过SQL创建XML文档,但是我收到语法错误

时间:2016-06-14 10:45:05

标签: sql xml oracle syntax-error

我有一个小的查询来制作XML文档:

Select XMLELEMENT(NAME movie,
XMLFOREST(Movie.name as title, year as year, rating as rating, plot_outline as plot, 
XMLELEMENT(NAME actor, 'actor',
XMLAGG(
XMLELEMENT(NAME role, Acts.role )
),
XMLAGG(
XMLELEMENT(NAME person, Person.name))   
)))
as result from Movie, Acts, Person
where Movie.mid = Acts.mid
and Acts.pid = Person.pid

但是我收到了这个错误:

ERROR:  unnamed XML element value must be a column reference
LINE 3:    XMLELEMENT(NAME actor, 'actor',
           ^

这应该是我在XML中的预期结果:

<movie>
<title>Godfather, The</title>
<year>1972</year>
<rating>9.0</rating>
<plot>A Mafia boss' son, previously uninvolved in the business, takes over when his father is critically wounded in a mob hit.</plot>
<actor>
<role>Don Vito Corleone</role>
<person>Robert De Niro</person>
</actor>
<actor>
<role>Someone else</role>
<person>Someone else</person>
</actor>

</movie>

如何摆脱此错误消息?

1 个答案:

答案 0 :(得分:0)

1)您可以在xmlelement中省略“name”字样。 xmlelment(name“name”...)= xmlelment(“name”...)。

2)未命名的XML元素值必须是列引用 - 该错误由xmlforest函数引发。

xmlforest( col1, col2 as "TEST") - works fine

xmlforest(col1,xmlelement("TEST")) - throws error should be xmlforest(col1,xmlelement("TEST") as "xxx" )

3)XMLELEMENT(NAME actor, 'actor'你不需要这个。如果我理解你的查询。您尝试将两个xmlagg连接成一个xmlelement。为此,请使用xmlconcat(xmlagg(..),xmlagg(..))

4)Finall查询。

   select xmlelement(
             movie
           , xmlforest(Movie.name as title
                     , year as year
                     , rating as rating
                     , plot_outline as plot
                     , xmlconcat(xmlagg(xmlelement(role, Acts.role)), xmlagg(xmlelement(person, Person.name))) as "actor"))
             as result
      from Movie, Acts, Person
     where Movie.mid = Acts.mid and Acts.pid = Person.pid

您还必须为其添加适当的group by子句。因为它引发了另一个例外。 ORA-00937:不是单组组功能