简体   繁体   中英

Oracle RTRIM of a listagg issue

I have a list of values that, as part of a dynamic query, form tuples for an in clause.

To do this, I have used a listagg, adding '),('1',' to each value, then using rtrim to remove the last value:

with r1 as
    (
    select 1 as id, 'XYZ1' as r_val
    from dual
    union all
    select 2, 'ABC1'
    from dual
    )
select rtrim(listagg(r1.r_val, 
                     '''),(''1'',''') within group (order by r1.r_val),
             '''),(''1'',''' )
from r1

Expected:

ABC1'),('1','XYZ1

However, for some reason, if the r_val ends with a 1 , the 1 is trimmed also:

ABC1'),('1','XYZ

Can anyone shed any light on this?

The characters for RTRIM() form a set, not a single string. So each is treated individually (see here ).

I don't see why the RTRIM() is needed at all for this query. listagg() only puts the separator string between values.

This should do what you want:

select listagg(r1.r_val, 
               '''),(''1'',''') within group (order by r1.r_val)
              )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM