sql语句中如何将字符类型转换成数字类型?

如题所述

先检查金额列的数据是否都符合小数规范,转为数字格式只有是数字的字符串才能转,如000012转为12,.55转为0.55,若是个英文符号等字符转了就报无效数字类型的错。

转换的方式很多,但是字符串转换成数字的前提是字符串中只包含了数字或者小数点。 

可使用convert函数,cast 和convert可以显式转换数据类型,在某些情况下SQL会根据实际情况自动转换!不过建议显式的转换一下,这样的话可读性高一点! 

因为字符串不一定能转换成数字,所以用上面的,加上错误处理比较。

例子:

declare @a varchar(10)

set @a='as23'

select case when isnumeric(@a)=1 then cast(@a as int) else null end

set @a='23'

select case when isnumeric(@a)=1 then cast(@a as int) else null end

结果:

declare @a varchar(10)

set @a='as23'

select case when isnumeric(@a)=1 then cast(@a as int) else null end

set @a='23'

select case when isnumeric(@a)=1 then cast(@a as int) else null end

温馨提示:答案为网友推荐,仅供参考
相似回答