zoukankan      html  css  js  c++  java
  • Oracle 中如何判断一个字符串是否为数字

    原地址:点击打开链接


    方法一:通过 To_Number 函数异常来判断

    CREATE OR REPLACE FUNCTION Is_Number (
       str_    VARCHAR2 ) RETURN VARCHAR2   
    IS     
       num_    NUMBER;          
    BEGIN     
      num_ := to_number(str_);         
      RETURN 'Y';     
    EXCEPTION   
       WHEN OTHERS THEN          
          RETURN 'N';     
    END Is_Number;   
    /

    SQL> select Is_Number('12345') from dual;
     
    IS_NUMBER('12345')
    --------------------------------------------------------------------------------
    Y
     
    SQL> select Is_Number('123.45') from dual;
     
    IS_NUMBER('123.45')
    --------------------------------------------------------------------------------
    Y
     
    SQL> select Is_Number('123a') from dual;
     
    IS_NUMBER('123A')
    --------------------------------------------------------------------------------
    N
     
    SQL>

     方法二:通过 translate函数来实现

    SELECT nvl2(translate('123','/1234567890','/'),'CHAR','NUMBER')   
    FROM   dual ;

    SQL> SELECT nvl2(translate('123','/1234567890','/'),'CHAR','NUMBER')
      2  FROM   dual;
     
    NVL2(TRANSLATE('123','/1234567
    ------------------------------
    NUMBER
     
    SQL> 
    SQL> SELECT nvl2(translate('123A','/1234567890','/'),'CHAR','NUMBER')
      2  FROM   dual;
     
    NVL2(TRANSLATE('123A','/123456
    ------------------------------
    CHAR
     
    SQL>

      在实际使用过程中,可以根据情况选用这两种方法。第一种方法的好处是可以判断带小数的数字,而第二种方法只能判断整数。因为如果 translate 函数如果写成 translate('123A','/1234567890.','/') 这种形式是会有问题的。

    SQL> select Is_Number('123.45.6') from dual;
     
    IS_NUMBER('123.45.6')
    --------------------------------------------------------------------------------
    N
     
    SQL> 
    SQL> SELECT nvl2(translate('1234.5.6','/1234567890.','/'),'CHAR','NUMBER')
      2  FROM   dual;
     
    NVL2(TRANSLATE('1234.5.6','/12
    ------------------------------
    NUMBER

    -----------------------------------------------

    SELECT TRANSLATE('2KRW229', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789') --把字符翻译成数字

    "Translate example"

    FROM DUAL;

    Translate example

    -----------------

    2229


  • 相关阅读:
    475. Heaters
    69. Sqrt(x)
    83. Remove Duplicates from Sorted List Java solutions
    206. Reverse Linked List java solutions
    100. Same Tree Java Solutions
    1. Two Sum Java Solutions
    9. Palindrome Number Java Solutions
    112. Path Sum Java Solutin
    190. Reverse Bits Java Solutin
    202. Happy Number Java Solutin
  • 原文地址:https://www.cnblogs.com/JSD1207ZX/p/9386282.html
Copyright © 2011-2022 走看看