DB2- How to check if varchar field value has integers

后端 未结 7 905
借酒劲吻你
借酒劲吻你 2020-12-10 02:58

Is there an inbuilt DB2 function or any query to check if the character i have is a number? (I cannot use user defined functions)

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 03:46

    I have made more error-prone version based on the idea xQbert exposed, added intermedia result, some examples and to_integer column which converts string value safely to integer:

    select 
          test_str
        ,                  TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), '           ', '0123456789'))
        , case when length(TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), '           ', '0123456789')))=0 
          then cast(test_str as int) else null end to_integer
        , case when length(TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), '           ', '0123456789')))=0 
          then 'integer'  else 'not integer' end is_integer
    from (VALUES 
            ('  123  '  )
            ,('  abc  ' )
            ,('  a12  ' )
            ,('  12 3  ')
            ,('  99.3  ')
            ,('993'     )
        ) AS X(test_str)
    ;
    

    The result for this example set is:

    TEST_STR 2        TO_INTEGER  IS_INTEGER
    -------- -------- ----------- -----------
      123                     123 integer
      abc    abc                - not integer
      a12    a                  - not integer
      12 3   x                  - not integer
      99.3   .                  - not integer
      993                     993 integer
    

提交回复
热议问题