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

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

    I had the same sort of need and found this to work well for me (postgres 8.4):

    CAST((COALESCE(myfield,'0')) AS INTEGER)
    

    Some test cases to demonstrate:

    db=> select CAST((COALESCE(NULL,'0')) AS INTEGER);
     int4
    ------
        0
    (1 row)
    
    db=> select CAST((COALESCE('','0')) AS INTEGER);
     int4
    ------
        0
    (1 row)
    
    db=> select CAST((COALESCE('4','0')) AS INTEGER);
     int4
    ------
        4
    (1 row)
    
    db=> select CAST((COALESCE('bad','0')) AS INTEGER);
    ERROR:  invalid input syntax for integer: "bad"
    

    If you need to handle the possibility of the field having non-numeric text (such as "100bad") you can use regexp_replace to strip non-numeric characters before the cast.

    CAST(REGEXP_REPLACE(COALESCE(myfield,'0'), '[^0-9]+', '', 'g') AS INTEGER)
    

    Then text/varchar values like "b3ad5" will also give numbers

    db=> select CAST(REGEXP_REPLACE(COALESCE('b3ad5','0'), '[^0-9]+', '', 'g') AS INTEGER);
     regexp_replace
    ----------------
                 35
    (1 row)
    

    To address Chris Cogdon's concern with the solution not giving 0 for all cases, including a case such as "bad" (no digit characters at all), I made this adjusted statement:

    CAST((COALESCE(NULLIF(REGEXP_REPLACE(myfield, '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
    

    It works similar to the simpler solutions, except will give 0 when the value to convert is non-digit characters only, such as "bad":

    db=> select CAST((COALESCE(NULLIF(REGEXP_REPLACE('no longer bad!', '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
         coalesce
    ----------
            0
    (1 row)
    

提交回复
热议问题