within case statements when both returns decimal with different scale
Not possible. A CASE
expression computes a value. The data type of the value it produces is determined via the data type precedence rules, but the values it can return have to all be converted to a single data type.
As to why it selects (38,2)
over (38,3)
, well, if it doesn't have enough bits available, it will always sacrifice scale over precision. See e.g. Precision, Scale and Length:
- The result precision and scale have an absolute maximum of 38. When a result precision is greater than 38, the corresponding scale is reduced to prevent the integral part of a result from being truncated.
The datatypes produced by the SUM()
calls are decimal(38,2)
and decimal(38,3)
. We can then use the same rules as included in the above link to work out what CASE
is going to do to determine its result type. The rules to follow are the ones specified for the e1 { UNION | EXCEPT | INTERSECT } e2
operation.
The result precision is given as max(s1, s2) + max(p1-s1, p2-s2)
- which is max(2,3) + max(38-2, 38-3)
- which is 3 + 36
which is 39
. As stated, since the maximum precision is 38
, we have to reduce the resultant scale.