Sql Decimal类型 运算结果的精度和小数位数
最近遇到一个问题,定义了三个Decimal(24,12)类型的变量,如:
declare @operand1 Decimal(24,12),@operand2 Decimal(24,12),@operand3 Decimal(24,12), @result Decimal(24,12) --@result 记录中间结果
设置变量值:
set @operand1=1;set @operand2=1;set @operand2=10000000;
三个变量进行运算: set @result =@operand1*@operand2/@operand3 ,计算结果@result=0.000000???为什么?
因为正常结果,或者说是我期望的结果应该是0.000000100000,应该是一个小数位数是12的Decimal(24,12)数值
因为习惯性的认为,操作数都定义为Decimal(24,12),操作结果应该是同类型数据。。。。。期间还尝试调整@operand1*@operand2/@operand3运算顺序,结果仍然是@result=0.000000!!!!
开始查询资料,最终看到CSDN一遍文章解释了详细的Decimal类型变量计算过程中精度和小数位数的计算方法
文章地址:https://blog.csdn.net/a544589668/article/details/7200206 (文章极为详细,这里简单引用作者的计算方法)
1. @d1+@d2,@d1-@d2
运算结果的精度 = max(s1,s2)+max(p1-s1,p2-s2)+1 --注:当值大于38时,取38
运算结果的小数位数
当精度值不大于38时 = max(p1,p2) --也就是取小数位数较大者
当精度值大于38时 = 38 - max(p1-s1,p2-s2)
2. @d1*@d2
运算结果的精度 = p1 + p2 + 1 --注:当值大于38时,取38
运算结果的小数位数
当精度值不大于38(或s1+s2<=6)时 = s1 + s2 --也就是取两者小数位数之和
当精度值大于38时 = max(6, s1+s2-(p1+p2+1-38))
3. @d1/@d2
运算结果的精度 = p1 - s1 + s2 + max(6, s1 + p2 + 1) --注:当值大于38时,取38
运算结果的小数位数
当精度值不大于38时 = max(6, s1 + p2 + 1)
当精度值大于38时 = max(6, s1+p2+1-(精度-38))
注:SQL_VARIANT_PROPERTY ( expression , property ),返回有关 sql_variant 值的基本数据类型和其他信息。通过此方法,可以查询Decimal类型的精度和小数位数,例:
select SQL_VARIANT_PROPERTY(@operand1,'Precision'),SQL_VARIANT_PROPERTY(@operand1,'Scale') --24,12