1

I've just been experimenting with the "between" statement in TSQL the following code returns "true":

declare @Value as decimal
declare @Upper as decimal
declare @Lower as decimal

set @Value = 20.1
set @Lower = 10.0
set @Upper = 20.0

select 
    case
    when @Value between @Lower and @Upper then 'true'
        else 'false'
    end as Result

If I change @Value to be 20.5, the result is "false", but 20.4 returns "true". It would appear that TSQL is using "banker's rounding" for decimal values.

If I change the variables to "money", I get the expected result, that is, @Value = 20.1 returns "false".

1
  • 2
    Using just decimal is equivalen to decimal(18,0) - with 0 digits after the decimal point. So therefore, you're digits after the comma are shaved off* and your values 20.0 and 20.1 become identical - 20 ....
    – marc_s
    Apr 8, 2015 at 4:46

2 Answers 2

5

Just to clarify a bit more what happened, had you simply printed your variables and you would have found out that their values were 20, 10 and 20 respectively.

decimal's default precision and scale are 18 and 0, so decimal = decimal(18,0). That's why you lost your decimals there. You didn't have this issue with money as it has a precision of 4 decimals.

Source: https://msdn.microsoft.com/en-us/library/ms187746.aspx

SQL is not using banker's rounding. .5 is always rounded up: 20.5 -> 21, 21.5 -> 22. With banker's rounding, 20.5 would be rounded to 20.

1
  • 2
    You're quite right, I should have output the variables, which would have made the problem obvious. I didn't know that about banker's rounding - helpful to know!
    – Billious
    Apr 8, 2015 at 2:29
4

I figured out what I was doing wrong. I forgot to specify the number of decimal points in the decimal variables. For example, the following code returns "false" as it should:

declare @Value as decimal(18,2)
declare @Upper as decimal(18,2)
declare @Lower as decimal(18,2)

set @Value = 20.1
set @Lower = 10
set @Upper = 20

select 
    case
        when @Value between @Lower and @Upper then 'true'
        else 'false'
    end as Result

Essentially, my original query was using whole numbers instead of floating-point values.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.