SQL 服务器保留对非常大的数字进行运算的十进制小数位和精度

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

之后,我仍在努力解决 SQL Server 2017 中的算术溢出错误。如何执行 multiplication/division 大 decimal(38,0) 值和 retain/regain精度和比例?

在我当前的示例中,我只想将 DECLARE @var1 decimal(38,0) = 85070591730234615865699536669866196992; 减半(如果 @var1 为奇数,则截断结果)。从 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. 我不知道如何回到 decimal(38,0)

此答案特定于您的特定问题 -- 除以 2。如果您想要更通用的解决方案,请提出新问题。

除以2等于乘以5再除以10

我们无法将您的值乘以 5,但我们可以执行以下操作:

  • 整数除以 10。
  • 乘以 5。
  • 添加一点额外的内容来弥补缺失的数字。

但是。 . .你在想。 . .我们如何除以 10?好吧,您可以使用 string 操作来做到这一点:只需截断最后一位数字:

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 是一个 db<>fiddle.