Oracle中的Sybase STR功能

时间:2013-11-22 14:30:19

标签: string oracle function sybase

是否与Sybase的STR-Function等效,后者将数字转换为字符串

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1510/html/iqrefbb/Str.htm

在Oracle中

?我找不到一个。如果没有,是否有一种优雅的方式来重现它?

非常感谢!

编辑:例如:

str(123.56,30,10) 
Sybase中的

给出一个总长度为30的字符串,正好在小数点后面10个位置,并在左边填充空格,结果是

                123.5600000000

2 个答案:

答案 0 :(得分:2)

select to_char(123.56, '99999999999999999999.00000000000')
from dual;

或更一般地(根据需要分别替换30和10):

select to_char(123.56, lpad(rpad('.',10,'0'),30,'9'))
from dual;

注意:字符串长度为31,以便为可能的“ - ”(负号)留出空间。

答案 1 :(得分:0)

由于oracle没有这样的特殊功能,你需要创建一个。所以,这一个会帮助你。也许需要一些改进来检查len是否大于小数位数。但这是一个好的开始。

create or replace function str( num in number, 
                                len in integer, 
                                decsLength in integer ) return varchar2 is
   decSep nls_database_parameters.value%type;
   befSep varchar2(255);
   aftSep varchar2(255); 
   finalStr varchar2(255);
begin

    --this gets the decimal separator, It depends on the 
    --database configuration.
    select substr(value, 2, 1) into decSep 
      from nls_database_parameters
     where parameter = 'NLS_NUMERIC_CHARACTERS';

    select substr( to_char(num), 1, 
                   decode( instr(to_char(num), decSep),              
                           0,
                           length(to_char(num)),
                           instr(to_char(num), decSep)-1) ) 
             into befSep from dual;

    select decode( instr(to_char(num), decSep), 
                   0, 
                   '', 
                   substr(to_char(num),
                          instr(to_char(num),decSep)+1)) 
           into aftSep from dual;

    if instr(to_char(num),decSep) > 0 then
        finalStr := lpad( befSep, len-(decsLength+1), ' ' ) 
                       || decSep || rpad(aftSep,decsLength, '0');
    else
        finalStr := lpad(befSep, len, ' ' );
    end if;

    return finalStr; 

end str;