Oracle SQL XMLAGG&quote;问题

9rygscc1  于 2022-11-28  发布在  Oracle
关注(0)|答案(2)|浏览(169)

我正在尝试将A聚合到一个字典列表中。Oracle的LISTAGG()可以工作,但确实达到了4k的最大字符数限制。我尝试使用XMLAGG,但现在我得到了“and quot;“而不是“"。请建议解决此问题的最佳方法。XMLCASTlistagg()的最终输出和解决方法是否相同?
| A级|不|
| - -|- -|
| {“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“5”:“"}|一个|
| {“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“6”:“}| 2个|
| {“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“7”:“}|三个|

select  
  --        '[' ||
  --        LISTAGG(cte.A, ' , ') WITHIN GROUP(
  --                ORDER BY
  --                    cte.N
  --            )
  --            || ']'
  '[' ||
  rtrim(xmlagg(xmlelement(e,cte.A,', ').extract('//text()') order by cte.N).getclobval(),', ')
  || ']' aggr_lsts
from cte;

错误输出:

[{"1":"09","2":"11","3":"2010","4":"XYZ","5":""}, {"1":"09","2":"11","3":"2010","4":"XYZ","6":""}, {"1":"09","2":"11","3":"2010","4":"XYZ","7":""}]

良好输出:

[{"1":"09","2":"11","3":"2010","4":"XYZ","5":""} , {"1":"09","2":"11","3":"2010","4":"XYZ","6":""} , {"1":"09","2":"11","3":"2010","4":"XYZ","7":""}]
  • 谢谢-谢谢
5cg8jx4n

5cg8jx4n1#

您可以使用xmlcast函数将XML数据正确地反序列化为clob。
请注意,XMLType方法自Oracle 11.2起已弃用,因此请改用XMLQUERYXMLCAST

with sample(col, rn) as (
  select column_value, rownum
  from sys.odcivarchar2list(
    '&',
    '>',
    '<',
    '"',
    'correctly serializable text'
  )
)
select
  rtrim(xmlcast(xmlquery(
    '//text()'
    passing xmlagg(
      xmlelement(e,col,', ')
      order by rn
    )
  returning content
  ) as clob), ', ') as res
from sample

| 保留|
| - -|
| &,〉,〈,“,可正确序列化的文本|
但对于12.2及以上版本,您可以直接使用JSON函数来生成正确的JSON数组:JSON_ARRAYAGG(如果我没记错的话,每个对象的JSON键数限制为32 k)。

with sample(col, rn) as (
  select column_value, rownum
  from sys.odcivarchar2list(
    '{"a": 1, "b": "2"}',
    '{"a": 2, "b": "qwe"}',
    '{"a": 3, "c": "test"}'
  )
)
select
  json_arrayagg(
    col order by rn
  ) as res
from sample

| 保留|
| - -|
| ["{“a”:1,“b”:“二”}",{“一”:2、“乙”:“qwe”}"、"{“甲”:3、“c”:“试验”}"]|
fiddle

9q78igpj

9q78igpj2#

不要对JSON数据使用XML函数。在Oracle 12.2中,使用JSONAGG来聚合行:

SELECT JSON_ARRAYAGG(a FORMAT JSON ORDER BY n RETURNING CLOB) As output
FROM   table_name
  • 注意:您需要FORMAT JSON来将您的输入视为有效的JSON,否则它将被视为字符串并被引用。您还需要RETURNING CLOB,否则默认的返回类型是VARCHAR2,它限制在4000个字符以内,并将产生与LISTAGG相同的问题。*

其中,对于示例数据:

CREATE TABLE table_name (A, N) AS
SELECT '{"1":"09","2":"11","3":"2010","4":"XYZ","5":""}', 1 FROM DUAL UNION ALL
SELECT '{"1":"09","2":"11","3":"2010","4":"XYZ","6":""}', 2 FROM DUAL UNION ALL
SELECT '{"1":"09","2":"11","3":"2010","4":"XYZ","7":""}', 3 FROM DUAL;

输出:
| 输出|
| - -|
| [{“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“5”:“},{“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“6”:“},{“1”:“09”,“2”:“11”,“3”:“2010”,“4”:“XYZ”,“7”:“}]|
fiddle

相关问题