views:

57

answers:

3
+3  Q: 

SQL Type-casting

I'm dividing some integers x & y in MS SQL, and I wan the result to be in a floating-point form. 5/2 should equal 2.5. When I simply do

SELECT 5/2

I get 2, which doesn't suprise me, since it's creating an int from two ints. I know I can force it to a float by doing:

SELECT CAST(5 AS FLOAT)/CAST(2 AS FLOAT);

but that seems like overkill. I find that I can just as easily (and much more readably) get the same result by using

SELECT (0.0+5)/2;

I'm guessing that this is just some sort of implicit type-casting? Is there some reason either method is better/worse?

+2  A: 

Under the covers there's no difference in implementation. The implicit casts accomplish the same thing as your explicit casts.

Jim Garrison
+2  A: 

Since you write 0.0, TSQL interprets this as float value. All following ints are implicitly cast to float.

See also the implicit data type conversion matrix in the section Implicit Conversions

devio
+1  A: 

Not sure something being shorter is more readable since true reading involves comprehension.

SELECT CAST(5 AS FLOAT)/CAST(2 AS FLOAT);

There really is no doubt what the intention is here and will be understood when you come back to the code 6 months from now or when another developer looks at it for the first time.

Jeff O
Thanks for the answer, JeffO! Note that I didn't claim it was more readable by merely "being shorter" - often when I'm looking at code which is a big mess of parenthesis/functions, I have a harder time seeing what it's doing "at a glance", as opposed to the last example I provided. But your point is taken - if you pull it apart, it IS more explicit what it's doing.Thanks again!
loneboat