SQL Server 2000 整数截断
问题描述:
简单明了,有人知道这是为什么吗:
Plain and simple, does anybody know why this:
Select 30 * 220 / 30
返回 220,这是正确的结果,并且:
Returns 220, which is the correct result, and this:
Select 30 * (220/30)
返回210???
在第二种情况下,我意识到首先计算 220/30,生成一个小数 (7,333333...) 但仍然...这不是很糟糕的精度吗?
On the second case, I realise that 220/30 is being calculated first, generating a decimal (7,333333...) but still... isn't this lousy precision?
答
在整数除法 220/30 = 7
和 99/100 = 0
下(注意截断不是四舍五入)
Under integer division 220/30 = 7
and 99/100 = 0
(note truncation not rounding)
使用非整数来避免这种情况.例如选择 30 * (220/30.0)
Use non integers to avoid this. e.g. Select 30 * (220/30.0)
或者你可以使用显式的cast
Select 30 * (220/cast (30 as float))