我试图在不使用REVERSE函数的情况下反转字符串。我遇到了一个例子:
select listagg(letter) within group(order by lvl)
from
(SELECT LEVEL lvl, SUBSTR ('hello', LEVEL*-1, 1) letter
FROM dual
CONNECT BY LEVEL <= length('hello'));
除了这种方法,还有其他更好的方法吗?
答案 0 :(得分:3)
如果您试图避免使用未记录的reverse()
功能,则可以使用utl_raw.reverse()
function代替,也可以使用RAW进行适当的转换:
select utl_i18n.raw_to_char(
utl_raw.reverse(
utl_i18n.string_to_raw('Some string', 'AL32UTF8')), 'AL32UTF8')
from dual;
UTL_I18N.RAW_TO_CHAR(UTL_RAW.REVERSE(UTL_I18N.STRING_TO_RAW('SOMESTRING','AL32UT
--------------------------------------------------------------------------------
gnirts emoS
所以这是一个原始的价值;对此进行utl_i18n.string_to_raw()
;然后将其传递给utl_raw.reverse()
;然后将结果传递回utl_i18n.raw_to_char()
。
不完全确定这将如何应对多字节字符,或者您想要发生在那些人身上......
或来自the discussion @RahulTripathi linked to的变体,没有字符集处理:
select utl_raw.cast_to_varchar2(utl_raw.reverse(utl_raw.cast_to_raw('Some string')))
from dual;
UTL_RAW.CAST_TO_VARCHAR2(UTL_RAW.REVERSE(UTL_RAW.CAST_TO_RAW('SOMESTRING')))
--------------------------------------------------------------------------------
gnirts emoS
但该线程还指出它只适用于单字节字符。
答案 1 :(得分:2)
你可以这样做:
with strings as (select 'hello' str from dual union all
select 'fred' str from dual union all
select 'this is a sentance.' from dual)
select str,
replace(sys_connect_by_path(substr (str, level*-1, 1), '~|'), '~|') rev_str
from strings
where connect_by_isleaf = 1
connect by prior str = str --added because of running against several strings at once
and prior sys_guid() is not null --added because of running against several strings at once
and level <= length(str);
STR REV_STR
------------------- --------------------
fred derf
hello olleh
this is a sentance. .ecnatnes a si siht
N.B。我使用了~|
的分隔符,因为这不太可能是你字符串的一部分。你需要为sys_connect_by_path提供一个非空的分隔符,因此我不能把它留空!
答案 2 :(得分:0)
您可以尝试使用此功能:
SQL> ed
Wrote file afiedt.buf
1 with t as (select 'Reverse' as txt from dual)
2 select replace(sys_connect_by_path(ch,'|'),'|') as reversed_string
3 from (
4 select length(txt)-rownum as rn, substr(txt,rownum,1) ch
5 from t
6 connect by rownum <= length(txt)
7 )
8 where connect_by_isleaf = 1
9 connect by rn = prior rn + 1
10* start with rn = 0
SQL> /
答案 3 :(得分:0)
SELECT LISTAGG(STR) WITHIN GROUP (ORDER BY RN DESC)
FROM
(
SELECT ROWNUM RN, SUBSTR('ORACLE',ROWNUM,1) STR FROM DUAL
CONNECT BY LEVEL <= LENGTH('ORACLE')
);