sql - MSSQL - union all with different decimal precision -


when execute sql

select 1.4 union select 2.0400 union select 1.24 

i following result:

1.4000
2.0400
1.2400

but when execute following sql

select sum(1.4) union select sum(2.0400) union select sum(1.24) 

i following result:

1.4
2.0
1.2

why there difference in precision (scale) applied records? shouldn't use precision no data loss, 1st sql?

thx.

i know quite old question, none of existing answers seem address "why?" aspect question.

first, data type literal expressions? wasn't sure (and didn't up) ran following:

select 1.4 union select 'frob' 

which returns error:

msg 8114, level 16, state 5, line 1
error converting data type varchar numeric.

okay, 1.4 , other literals numeric - a.k.a decimal.

next, return type of sum function, if passed decimal(p,s)1:

decimal(38, s)

okay, data types of 3 sum expressions in query decimal(38,1), decimal(38,4) , decimal(38,2). given 3 data types available pick from, decimal(38,1) final chosen type, based on rules differing precisions , scales.

the result precision , scale have absolute maximum of 38. when result precision greater 38, corresponding scale reduced prevent integral part of result being truncated.

so, finally, documentation on decimal:

by default, sql server uses rounding when converting number decimal or numeric value lower precision , scale. however, if set arithabort option on, sql server raises error when overflow occurs. loss of precision , scale not sufficient raise error.

so that's final result.


1 @ first type may seem surprising, until realise generally, sum operate against multiple rows , it's possible multiple values of given precision , scale overflow own data type. decimal(38,s) gives largest possible space accommodate overflows without losing precision, particular sum() occurrence, , means final data type can decided upon before query has executed.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -