I really hope some SQL guru out there can assist with this one (and my apologies if this has been answered before. I did try and find a similar post but to no avail):
declare @theanswer numeric(38,16)
select @theanswer = 0.01 / 0.0074464347
select @theanswer
The above results in 1.3429245542165000
but the following (which looks the same to me)
declare @val1 numeric(38,16);
declare @val2 numeric(38,16);
set @val1 = 0.01;
set @val2 = 0.0074464347;
select @val1/@val2
results with 1.342924 and truncates it?
Any ideas?
To get the real precision and scale for the result (@val1/@val2) I would execute this
T-SQLscriptAnd the results will be:
So, the result precision is 38 and result scale is 6.
MSDN has some details regarding precision and scale for arithmetic operations. These information can be found here: Precision, Scale, and Length (Transact-SQL):
Using these formulas we can write the next
T-SQLscript to get theoretical precision and scale for the result (@val1/@val2) :The result is:
So, for this arithmetic operation (@val1/@val2), in
theorythe precision and scale are93and55but the real precision and scale are38and6.The real precision is 38 because “The result precision and scale have an absolute maximum of 38“.
Regarding the real result scale (6) MSDN it’s not clear: “When a result precision is greater than 38, the corresponding scale is reduced to prevent the integral part of a result from being truncated”.
To see how “the corresponding scale is reduced” I executed the above tests (script 1 for real precision and scale and script 2 for theoretical precision and scale) using
NUMERICvalues having the same scale (16) but different scales (from 16 to 38). The results of these tests are:Examining these results:
1.I see an arithmetic progression for the real result scale: from 22 to 6, step -1.
2.Also, if the scale for @val1 and @val2 is constant (
NUMERIC(...,16)) then an inverse correlation exists between @val1 & @val2 precision (from 16 to 32) and the [real] result scale (from 16 to 6).3.If @val1 and @val2 precision is 32 or higher (
NUMERIC(32->38,16)) the the [real] result scale is always 6 => this is your case.4.If a greater [real] result scale is needed (over 6) you need to use a lower precision for @val1
and @val2:
NUMERIC(22, 16):