简体   繁体   中英

t-sql: What is the best way to compare against decimals

In my query I need to get records where percentage is less then 50%.

The field that stores percentage values are defined as char(3) . For example, I see some data defined as '.35'

In my query I used a condition where mypercentagevalue < '.50' , but it will not work as I noticed that the field also has values such as '85', '95', '90' and etc

Would can I use to compare against all cases

Thank you

Eugene - since this field is defined as char(3), do the following:

first - make sure you have a number in the field with a case statement and the IsNumeric function. Then cast it to a number.

select * from [dbo].[YourTable]
where cast(case isnumeric([YourField]) when 0 then 0 else [YourField] end as numeric(9,2)) < .5

Whole numbers (85,90, etc...) will show up in the results until you get your data formatted correctly.

I agree with @Eugene.it and @JNK but if for some reason (and I can't think of a good one) you can't fix the data then you could use something like below.

WHERE .5 > CASE WHEN CAST(mypercentagevalue as decimal (6,2)) >= 1 THEN CAST(mypercentagevalue as decimal (6,2))/100 ELSE CAST(mypercentagevalue as decimal (6,2)) END

I would do something like the following though.

UPDATE #temp
SET mypercentagevalue = CASE WHEN CAST(mypercentagevalue as decimal (6,2)) >= 1 THEN
                                  CAST(mypercentagevalue as decimal (6,2))/100 
                                  ELSE CAST(mypercentagevalue as decimal (6,2)) END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM