My question is pretty simple but I'm not sure if it's possible.
Assume I have a table and it contains the column below
PokemonHappiness smallint
Is it possible to set a maximum value for that column?
For instance if I set the maximum to 10000 and send a query like this
--Assume that PokemonHappiness is equal to 9990
update mytable set PokemonHappiness = PokemonHappiness+50
it should become 10000 instead of 10040
Is this possible?
When you want to set it to 10000 then don't set it to 10040. Your "auto-update" would have side-effect and would be very error-prone(consider that you'll forget it or someone doesn't know it). But you could use a
CASE
:If you want to set a maximum value on a column of a SQL table, one thing you can do is add a
CHECK
constraint with specific criteria for that column:However, this won't handle out-of-bounds input in a graceful fashion; if your input violates the
CHECK
constraint, SQL will simply throw an error.To properly handle this sort of input, you should probably use a
CASE
expression as others suggest, and maybe use aCHECK
constraint as a hard bound to what can be inserted (just in case of unmoderated input values).A trigger. I tested this.
You can achieve that with this
OR with two queries