Oracle - 将字符串与utl_raw.cast_to_varchar2函数的结果连接起来

时间:2017-05-09 12:26:44

标签: oracle oracle11g

我试图将字符串连接到utl_raw.cast_to_varchar2函数的结果(也是一个字符串)。它应该是透明的,但我无法将任何内容附加到utl_raw.cast_to_varchar2的结果。

以下是一个例子:

select  utl_raw.cast_to_varchar2((nlssort('"' || CITY_NAME || ', ' || STATE_CODE || '"', 'nls_sort=binary_ai'))) || ' test' 
from (select 'New York' as CITY_NAME, 'NY' as STATE_CODE from dual)

我希望结果为"new york, ny" test,但我只得到"new york, ny"

1 个答案:

答案 0 :(得分:4)

这是可能被视为错误的组合 - 但实际上对于Oracle内部使用nlssort的方式实际上至关重要 - 以及客户端如何处理字符串。例如,在SQL Developer中,这似乎在作为语句或脚本时可以正常工作,但我无法从工作表或查询结果网格中复制和粘贴结果。

使用dump()功能,您可以看到构成结果的字符:

select dump(utl_raw.cast_to_varchar2((nlssort('"' || CITY_NAME || ', ' || STATE_CODE || '"',
  'nls_sort=binary_ai'))) || ' test', 1016) as dumped_result
from (select 'New York' as CITY_NAME, 'NY' as STATE_CODE from dual);

DUMPED_RESULT                                                                                       
----------------------------------------------------------------------------------------------------
Typ=1 Len=20 CharacterSet=AL32UTF8: 22,6e,65,77,20,79,6f,72,6b,2c,20,6e,79,22,0,20,74,65,73,74
                                                                              ^

我标记了一个^标记,以突出显示在该输出中的0,在投射nlssort()结果和您要添加的test之间。或者更清楚一点没有连接:

select dump(utl_raw.cast_to_varchar2(nlssort('ABC')), 1016) as dumped_result
from (select 'New York' as CITY_NAME, 'NY' as STATE_CODE from dual);

DUMPED_RESULT                                                                                       
----------------------------------------------------------------------------------------------------
Typ=1 Len=4 CharacterSet=AL32UTF8: 41,42,43,0

甚至更好:

select dump(nlssort('ABC'), 1016) as dumped_result from dual;

DUMPED_RESULT                                                                                       
----------------------------------------------------------------------------------------------------
Typ=23 Len=4: 41,42,43,0

nlssort()调用正在向结果中添加一个空字节(在转储输出中显示为0)。您的客户端将其视为字符串的结尾,因此即使Oracle实际上连接字符串,您也无法看到结果。

您可以删除null,例如在连接之前使用rtrim()

select rtrim(utl_raw.cast_to_varchar2(nlssort('"' || CITY_NAME || ', ' || STATE_CODE || '"',
  'nls_sort=binary_ai')), chr(0)) || ' test' as result
from (select 'New York' as CITY_NAME, 'NY' as STATE_CODE from dual);

RESULT                                                                                              
----------------------------------------------------------------------------------------------------
"new york, ny" test

或使用较短的原始字符串:

select dump(rtrim(utl_raw.cast_to_varchar2(nlssort('ABC')), chr(0)), 1016) as dumped_result
from (select 'New York' as CITY_NAME, 'NY' as STATE_CODE from dual);

DUMPED_RESULT                                                                                       
----------------------------------------------------------------------------------------------------
Typ=1 Len=3 CharacterSet=AL32UTF8: 41,42,43
你现在可以看到的

没有尾随空字符。