【发布时间】:2018-08-23 08:15:06
【问题描述】:
我正在尝试基于 Oracle SQL 中的查询创建一些 xml。如果您进行 1 对 1 的转换,这非常容易,但是我需要围绕返回的 xml 创建一个分组元素。这是我的工作代码。
WITH table2 AS (
SELECT t.id
FROM table1 t
WHERE t.code = 'somevalue')
select xmlelement("mes:tests",
xmlattributes('http://testnamespace.com/' as "xmlns:tns"),
xmlagg(xmlelement("tns:test",
xmlelement("tns:ID", id))))
from table2;
问题在于,在这种情况下,即使没有数据,它也会返回一个空的测试元素。我需要它返回NULL。到目前为止,我已经尝试了几件事。比如这个案例:
WITH table2 AS (
SELECT t.id
FROM table1 t
WHERE t.code = 'somevalue')
select CASE WHEN exists(select id from table2) THEN
xmlelement("mes:tests",
xmlattributes('http://testnamespace.com/' as "xmlns:tns"),
xmlagg(xmlelement("tns:test",
xmlelement("tns:ID", id)))) ELSE null end
from table2;
但是这会产生错误:
not a single-group group function
任何人都知道我可以做到这一点的好方法吗?我正在使用 Oracle DB 12c。
【问题讨论】:
-
样本数据和当前/预期结果会很有用。例如,您是否有多个与代码匹配的 ID - 使用 XMLAgg 会建议您这样做,但如果没有,则可能不需要。