check if “it's a number” function in Oracle

后端 未结 16 2805
一整个雨季
一整个雨季 2020-11-28 10:31

I\'m trying to check if a value from a column in an oracle (10g) query is a number in order to compare it. Something like:

select case when ( is_number(myTab         


        
16条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 11:03

    Here's a simple method which :

    • does not rely on TRIM
    • does not rely on REGEXP
    • allows to specify decimal and/or thousands separators ("." and "," in my example)
    • works very nicely on Oracle versions as ancient as 8i (personally tested on 8.1.7.4.0; yes, you read that right)
    SELECT
        TEST_TABLE.*,
    
        CASE WHEN
            TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a.,0123456789', 'a') IS NULL
        THEN 'Y'
        ELSE 'N'
        END
        AS IS_NUMERIC
    
    FROM
        (
        -- DUMMY TEST TABLE
            (SELECT '1' AS TEST_COLUMN FROM DUAL) UNION
            (SELECT '1,000.00' AS TEST_COLUMN FROM DUAL) UNION
            (SELECT 'xyz1' AS TEST_COLUMN FROM DUAL) UNION
            (SELECT 'xyz 123' AS TEST_COLUMN FROM DUAL) UNION
            (SELECT '.,' AS TEST_COLUMN FROM DUAL)
        ) TEST_TABLE
    

    Result:

    TEST_COLUMN IS_NUMERIC
    ----------- ----------
    .,          Y
    1           Y
    1,000.00    Y
    xyz 123     N
    xyz1        N
    
    5 rows selected.
    

    Granted this might not be the most powerful method of all; for example ".," is falsely identified as a numeric. However it is quite simple and fast and it might very well do the job, depending on the actual data values that need to be processed.

    For integers, we can simplify the Translate operation as follows :

    TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a0123456789', 'a') IS NULL
    

    How it works

    From the above, note the Translate function's syntax is TRANSLATE(string, from_string, to_string). Now the Translate function cannot accept NULL as the to_string argument. So by specifying 'a0123456789' as the from_string and 'a' as the to_string, two things happen:

    • character a is left alone;
    • numbers 0 to 9 are replaced with nothing since no replacement is specified for them in the to_string.

    In effect the numbers are discarded. If the result of that operation is NULL it means it was purely numbers to begin with.

提交回复
热议问题