tags:

views:

63

answers:

1

Hi, I am updating my table with the following statement:

UPDATE table SET percentage = percentage + ? WHERE id = ?

And the value that is being passed to the database may be positive and negative as well.

Is there a way to make sure that the percentage value is going to lie in the range of 0..100? Desirable to accomplish it, using only SQLite.

If it is less than 0 I want to make it 0; If it is more than 100 I want to make it 100.

I can have it done through my C code, but it would be better to have it done through SQLite.

Thank you in advance.

+1  A: 
UPDATE table SET percentage 
= case when percentage < 0 then 0 
  when percentage > 100 then 100 
  else percentage end
WHERE id = ?;

If you leave off the where clause, you'll set percentages for the entire table, which is presumably what you want.

However, it may be that percentages greater than 100 or less than zero are legitimate; I don't know your problem domain.

tpdi
Thank you, I did the following: "UPDATE table SET percentage = case WHEN (percentage + ?) < 0 then 0 WHEN (percentage + ?) > 100 then 100 ELSE (percentage + ?) END WHERE word_id = ?";Do I have to bind the same value for all 3 symbols "?" ? Or there is a way to do it once?
Ilya
You don't need to bind anything except the id. Use the statement I gave you /as-is/. Or you can omit the where clause, and use it.
tpdi