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

前端 未结 13 952
误落风尘
误落风尘 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:50

    This might be somewhat of a hack, but it got the job done in our case:

    (0 || myfield)::integer
    

    Explanation (Tested on Postgres 8.4):

    The above mentioned expression yields NULL for NULL-values in myfield and 0 for empty strings (This exact behaviour may or may not fit your use case).

    SELECT id, (0 || values)::integer from test_table ORDER BY id
    

    Test data:

    CREATE TABLE test_table
    (
      id integer NOT NULL,
      description character varying,
      "values" character varying,
      CONSTRAINT id PRIMARY KEY (id)
    )
    
    -- Insert Test Data
    INSERT INTO test_table VALUES (1, 'null', NULL);
    INSERT INTO test_table VALUES (2, 'empty string', '');
    INSERT INTO test_table VALUES (3, 'one', '1');
    

    The query will yield the following result:

     ---------------------
     |1|null        |NULL|
     |2|empty string|0   |
     |3|one         |1   |
     ---------------------
    

    Whereas select only values::integer will result in an error message.

    Hope this helps.

提交回复
热议问题