Reputation: 13651
I have this statement
UPDATE table SET health = health + 1 WHERE name='Tom'
How can I set a MAX for the number field in the statement based off? Pseudo code:
UPDATE table set health = min(health+1, max_health) WHERE name='Tom'
Upvotes: 0
Views: 50
Reputation: 5656
We can use CASE
also
UPDATE table
SET health = (CASE WHEN health+1 < max_health THEN
health+1
ELSE
max_health
END) WHERE name='Tom'
AND IIF
--SQL Server
UPDATE table SET health = IIF (health+1 < max_health, health+1, max_health) WHERE name='Tom'
Upvotes: 0
Reputation: 1270553
The simplest way is to modify the where
:
UPDATE table
SET health = health + 1
WHERE name = 'Tom' AND health < max_health;
Some databases support the least()
function:
UPDATE table
SET health = LEAST(health + 1, max_health)
WHERE name = 'Tom' ;
You can also do this using CASE
.
However, I think the first method is the simplest.
Upvotes: 1