我有这个陈述
UPDATE table SET health = health + 1 WHERE name='Tom'
如何根据关闭语句中的数字字段设置MAX?伪代码:
UPDATE table set health = min(health+1, max_health) WHERE name='Tom'
答案 0 :(得分:1)
最简单的方法是修改where
:
UPDATE table
SET health = health + 1
WHERE name = 'Tom' AND health < max_health;
某些数据库支持least()
功能:
UPDATE table
SET health = LEAST(health + 1, max_health)
WHERE name = 'Tom' ;
您也可以使用CASE
。
但是,我认为第一种方法最简单。
答案 1 :(得分:0)
我们也可以使用CASE
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'