Friday, November 10, 2017

integer division versus real division in T-SQL

Dividing integers by integers will give integers for results. In the event of a non-even split in which there is a remainder, an error is not thrown. Instead, SQL just deals with it with rounding to the nearest integer. Surreally, this can produce scenarios is which you may divide not zero by not zero and end up with zero which should be impossible. The fix is to cast the denominator of your "fraction" (that which you will divide by not that which you will divide) to a float just before the cutting like so:

SELECT Foo, Bar, Baz, (Foo + Bar) / CAST(Baz as float) * 100 as Qux
FROM Whatever

No comments:

Post a Comment