SQL反模式笔记9——取整错误

目标:使用小数取代整数

反模式:使用float

  float类型是使用二进制格式编码实数数据。并不是所有的十进制数都能用二进制存储,所以浮点数通常是舍入到了一个非常接近的值。

  比如:

  select rate from A where id=123   --Result:59.95

  select * from A where rate=59.95 --Result:empty set;no rows match.

  select * from A where ABS(rate-59.95)<0.000001   --这个才能正确查出数据!

识别反模式:

  使用float、real。

合理使用反模式:

  如果要存储的值取值范围很大,大过了integer、numeric的范围,那只能用float了。科学计算类的程序通常使用float。

解决方案:

  使用numeric、decimal代替float,他们不会对存储的有理数进行舍入,因此select * from A where rate=59.95会返回记录。

  注意:numeric、decimal在sqlserver乃至sybase中,是完全一样的。

posted @ 2012-05-07 09:12  日暮乡关何处是  阅读(338)  评论(0编辑  收藏  举报