Let's say I have the following data in a decimal (18,9)
identity column in a database table:
ID
========
1000.00
1001.23
1002.00
1003.23
I want to write a SQL query that returns only those records that have .230000000
for the right side of the decimal place, such that only the following are returned:
1001.23
1003.23
I know I could do this by converting it to a string a doing a string comparison, but is there a better way that doesn't involve string comparison and is more efficient at handling numeric values?
Based on Martin's answer, I think the best solution to use is like so:
Abs(ID - Cast(ID As int))
I added the Abs()
function to work with negative numbers.
I ran the following tests to make sure I wasn't getting wierd rounding errors:
Declare @ID decimal(18,9)
Set @ID = 1000.000000000
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: 1000.000000000 0.000000000
Set @ID = -1000.000000000
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: -1000.000000000 0.000000000
Set @ID = 1000.000000001
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: 1000.000000001 0.000000001
Set @ID = -1000.000000001
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: -1000.000000001 0.000000001
Set @ID = 1000.999999999
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: 1000.999999999 0.999999999
Set @ID = -1000.999999999
Select @ID, Abs(@ID - Cast(@ID As int))
-- Returns: -1000.999999999 0.999999999