是否有一个内置的DB2功能或任何查询,检查,如果我有一个字符是数字? (我不能使用用户定义的功能)
Answer 1:
文件链接
CASE
WHEN LENGTH(RTRIM(TRANSLATE(test_str, '*', ' 0123456789'))) = 0
THEN 'All digits'
ELSE 'No'
END
Answer 2:
有许多方法。 采取只使用两个函数来看看该解决方案:
CASE
WHEN REPLACE(TRANSLATE(test_str, '0','123456789','0'),'0','') = ''
THEN 'All digits'
ELSE 'Not all digits'
END
在一般 - 更少的功能 - 更好的性能:)
Answer 3:
使用ASCII函数来获取字符值和比较,这是48“0”和57“9”之间
ASCII表
ASCII函数返回参数作为整数的最左边的字符的ASCII码值。
Answer 4:
如果你的DB2版本可以使用REGEXP_LIKE你可以做到这一点:
用数字“” 作为小数点符号:
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+(\.\d*)?$')
用数字“”作为小数点符号:
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+(\,\d*)?$')
不带小数点符号数(仅整数,你问)
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+$')
Answer 5:
通过xQbert答案不完全正确。 你真正需要的是在fromString每个字符*(和空间需要被删除),的字符串长度必须是一样的原始字符串的长度。
因此它看起来就像这样:
CASE
WHEN LENGTH(RTRIM(TRANSLATE(test_str, '**********', '0123456789'))) = LENGTH(RTRIM(test_str))
THEN 'All digits'
ELSE 'No'
END
Answer 6:
返回数值,其中焦炭领域是没有前导或尾随空格所有数字。 即; 在现场所有字符都是数字:
where translate(char_field, 'X ',' 0123456789') = ' '
返回与考虑非数字的前导空格非数字值,但是拖尾的空格被忽略。 即; 非数字如果有前导空格,但如果有尾随空格。 这是为主机/ COBOL加载字段经常发生的:
where not ( length(rtrim(translate(substr(char_field,1,length(rtrim(char_field))),' ','0123456789'))) = 0)
返回数值与价值后尾随,但不前导空格。 即; 前导空格被视为非数字,但是拖尾的空格被忽略。 此外,常见的主机/ COBOL CHAR字段:
where ( length(rtrim(translate(substr(char_field,1,length(rtrim(char_field))),'X ',' 0123456789'))) = 0)
返回数值与领先及尾随空格。 即; 忽略前导和在确定字段尾随空格是“数字”:
where ( length(ltrim(rtrim(translate(substr(char_field,1,length(ltrim(rtrim(char_field)))),' ','0123456789')))) = 0)
Answer 7:
我已经根据曝光的想法xQbert更容易出错的版本,增加中间结果,一些例子,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)
;
在这个例子中设置的结果是:
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
文章来源: DB2- How to check if varchar field value has integers