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

前端 未结 13 905
误落风尘
误落风尘 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 07:09

    @Matthew's answer is good. But it can be simpler and faster. And the question asks to convert empty strings ('') to 0, but not other "invalid input syntax" or "out of range" input:

    CREATE OR REPLACE FUNCTION convert_to_int(text)
      RETURNS int AS
    $func$
    BEGIN
       IF $1 = '' THEN  -- special case for empty string like requested
          RETURN 0;
       ELSE
          RETURN $1::int;
       END IF;
    
    EXCEPTION WHEN OTHERS THEN
       RETURN NULL;  -- NULL for other invalid input
    
    END
    $func$  LANGUAGE plpgsql IMMUTABLE;
    

    This returns 0 for an empty string and NULL for any other invalid input.
    It can easily be adapted for any data type conversion.

    Entering an exception block is substantially more expensive. If empty strings are common it makes sense to catch that case before raising an exception.
    If empty strings are very rare, it pays to move the test to the exception clause.

    0 讨论(0)
提交回复
热议问题