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

后端 未结 16 2764
一整个雨季
一整个雨季 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 10:58

    Assuming that the ID column in myTable is not declared as a NUMBER (which seems like an odd choice and likely to be problematic), you can write a function that tries to convert the (presumably VARCHAR2) ID to a number, catches the exception, and returns a 'Y' or an 'N'. Something like

    CREATE OR REPLACE FUNCTION is_number( p_str IN VARCHAR2 )
      RETURN VARCHAR2 DETERMINISTIC PARALLEL_ENABLE
    IS
      l_num NUMBER;
    BEGIN
      l_num := to_number( p_str );
      RETURN 'Y';
    EXCEPTION
      WHEN value_error THEN
        RETURN 'N';
    END is_number;
    

    You can then embed that call in a query, i.e.

    SELECT (CASE WHEN is_number( myTable.id ) = 'Y' AND myTable.id > 0 
                   THEN 'Number > 0'
                 ELSE 'Something else'
             END) some_alias
      FROM myTable
    

    Note that although PL/SQL has a boolean data type, SQL does not. So while you can declare a function that returns a boolean, you cannot use such a function in a SQL query.

提交回复
热议问题