SQL Server retain decimal scale and precision for operations on very lage numbers

眉间皱痕 提交于 2020-04-30 06:28:40

问题


Following my previous question I am still struggling with an arithmetic overflow error in SQL Server 2017. How can I perform a multiplication/division of a large decimal(38,0) value and retain/regain both the precision and scale?

In my current example I simply want to halve DECLARE @var1 decimal(38,0) = 85070591730234615865699536669866196992; (and truncate the result if @var1 were odd). From this post I have gathered that even if I do not attempt to divide by 2 but multiply by 0.5 instead I would still not obtain a decimal(38,0) result. I could divide by 2,000,000 to make the result fit the resulting decimal(38,6) type, but considering the multiplication rules etc. I can't figure out how to get back to decimal(38,0).


回答1:


This answer is specific to your specific question -- dividing by 2. If you want a more general solution, please ask a new question.

Dividing by 2 is the same as multiplying by 5 and dividing by 10.

We cannot multiply your value by 5, but we can do the following:

  • Integer divide by 10.
  • Multiply by 5.
  • Add in a little bit extra to account for the missing digit.

But . . . you are thinking . . . how can we divide by 10? Well, you can do that with string operations: just truncate the last digit:

declare @var1 decimal(38,0) = 85070591730234615865699536669866196992;

select (convert(decimal(38,0), left(convert(varchar(38), @var1), 37)) * 5 +
        convert(decimal(38, 0), (@var1 % 10) / 2)
       ) as half_a_big_value

Here is a db<>fiddle.



来源:https://stackoverflow.com/questions/61505606/sql-server-retain-decimal-scale-and-precision-for-operations-on-very-lage-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!