如果查询包含记录,则从查询创建xml

时间:2018-08-23 08:15:06

标签: case oracle12c sqlxml oracledb

我正在尝试基于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。

1 个答案:

答案 0 :(得分:1)

根据您的描述,您可以将exists支票更改为count

select CASE WHEN count(id) > 0 THEN 
 xmlelement("mes:tests",
        xmlattributes('http://testnamespace.com/' as "xmlns:tns"),
        xmlagg(xmlelement("tns:test",
            xmlelement("tns:ID", id)))) ELSE null end
    from table2;

具有另一个CTE的示例数据的演示,没有匹配项:

set null "(null)"

WITH table1(id, code) as (
      select 42, 'ignore' from dual),
table2 AS (
      SELECT t.id
      FROM   table1 t
      WHERE t.code = 'somevalue')

select CASE WHEN count(id) > 0 THEN 
 xmlelement("mes:tests",
        xmlattributes('http://testnamespace.com/' as "xmlns:tns"),
        xmlagg(xmlelement("tns:test",
            xmlelement("tns:ID", id)))) ELSE null end
    from table2;

CASEWHENCOUNT(ID)>0THENXMLELEMENT("MES:TESTS",XMLATTRIBUTES('HTTP://TESTNAMESPAC
--------------------------------------------------------------------------------
(null)

并具有匹配项:

WITH table1(id, code) as (
      select 42, 'somevalue' from dual union all
      select 43, 'somevalue' from dual),
table2 AS (
      SELECT t.id
      FROM   table1 t
      WHERE t.code = 'somevalue')

select CASE WHEN count(id) > 0 THEN 
 xmlelement("mes:tests",
        xmlattributes('http://testnamespace.com/' as "xmlns:tns"),
        xmlagg(xmlelement("tns:test",
            xmlelement("tns:ID", id)))) ELSE null end
    from table2;

CASEWHENCOUNT(ID)>0THENXMLELEMENT("MES:TESTS",XMLATTRIBUTES('HTTP://TESTNAMESPAC
--------------------------------------------------------------------------------
<mes:tests xmlns:tns="http://testnamespace.com/"><tns:test><tns:ID>42</tns:ID></
tns:test><tns:test><tns:ID>43</tns:ID></tns:test></mes:tests>