How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

前端 未结 13 954
误落风尘
误落风尘 2020-12-02 06:27

In PostgreSQL I have a table with a varchar column. The data is supposed to be integers and I need it in integer type in a query. Some values are empty strings. The followin

13条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 06:53

    You could also create your own conversion function, inside which you can use exception blocks:

    CREATE OR REPLACE FUNCTION convert_to_integer(v_input text)
    RETURNS INTEGER AS $$
    DECLARE v_int_value INTEGER DEFAULT NULL;
    BEGIN
        BEGIN
            v_int_value := v_input::INTEGER;
        EXCEPTION WHEN OTHERS THEN
            RAISE NOTICE 'Invalid integer value: "%".  Returning NULL.', v_input;
            RETURN NULL;
        END;
    RETURN v_int_value;
    END;
    $$ LANGUAGE plpgsql;
    

    Testing:

    =# select convert_to_integer('1234');
     convert_to_integer 
    --------------------
                   1234
    (1 row)
    
    =# select convert_to_integer('');
    NOTICE:  Invalid integer value: "".  Returning NULL.
     convert_to_integer 
    --------------------
    
    (1 row)
    
    =# select convert_to_integer('chicken');
    NOTICE:  Invalid integer value: "chicken".  Returning NULL.
     convert_to_integer 
    --------------------
    
    (1 row)
    

提交回复
热议问题