【问题标题】:Limit listagg function to first 4000 characters [duplicate]将listagg函数限制为前4000个字符[重复]
【发布时间】:2015-04-02 19:09:27
【问题描述】:

我有一个查询,它使用listagg 函数将所有行作为逗号分隔的字符串最终发送到一个大文本框。我收到以下异常:

ORA-01489: result of string concatenation is too long

我知道问题在于,为聚合数据而运行的查询返回了太多行,以至于 listagg 正在执行的字符串连接违反了 4000 个字符的限制。但是,对于我的用例,截断到前 4000 个字符是完全可以接受的。

如何从here 修改此示例查询以将“值”列限制为最多 4000 个字符?

SELECT LISTAGG(product_name, ', ') WITHIN GROUP( ORDER BY product_name DESC) "Product_Listing" FROM products

您不能将 substr 包裹在调用 listagg' becauselistaggthrows the exception beforesubstr` 周围。

我在 SO 上看到了很多关于如何绕过 4000 个字符限制但不限制结果值的问题。

【问题讨论】:

    标签: sql oracle oracle11g string-concatenation varchar2


    【解决方案1】:

    12.2及以上

    ON OVERFLOW 选项可以轻松处理超过 4000 个字符:

    select listagg(product_name, ',' on overflow truncate) within group (order by product_name)
    from products;
    

    11.2 到 12.1

    解析函数可以生成字符串聚合的运行总长度。然后内联视图可以删除长度大于 4000 的任何值。

    在实际查询中,您可能需要将partition by 添加到分析函数中,以便仅按某些组计数。

    --The first 4000 characters of PRODUCT_NAME.
    select
        --Save a little space for a ' ...' to imply that there is more data not shown.
        case when max(total_length) > 3996 then
            listagg(product_name, ', ') within group (order by product_name)||
                ' ...'
        else
            listagg(product_name, ', ') within group (order by product_name)
        end product_names
    from
    (
        --Get names and count lengths.
        select
            product_name,
            --Add 2 for delimiters.
            sum(length(product_name) + 2) over (order by product_name) running_length,
            sum(length(product_name) + 2) over () total_length
        from products
        order by product_name
    )
    where running_length <= 3996
    

    这是一个 SQL Fiddle 演示查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 2019-05-08
      相关资源
      最近更新 更多