Why, when you run this, do you get 2.00 as the answer?
declare @temp int = 2
select CASE WHEN @temp = 1 THEN cast(@temp as decimal(5, 2))
WHEN @temp = 2 THEN @temp
ELSE NULL
END
But if you run this, you get 2 as the answer when selecting just @temp2
declare @temp2 int = 2
select CAST(@temp2 as decimal(5,2))
select @temp2
Bridge is correct:
Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. (Source)
I believe the return value has to be the same datatype for each possible output from the case statement. It considers the possible outputs, and tries to cast them all to the same type.
The first possible return value there is of type
decimal(5, 2), and second of typeint. It chooses the datatype with the highest presidence that can hold both values, and automatically casts all the outputs to this for you.Your second script is behaving as expected. You actually get two values output:
2.00– which is the result of the cast in the second line2– which is the value of @temp2 – which is an int, you assigned it on the first line