Is it possible to set a maximum value for a column in SQL Server 2008 r2

余生长醉 提交于 2019-12-12 05:31:58

问题


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?


回答1:


A trigger. I tested this.

CREATE TRIGGER dbo.Table_2update
ON dbo.Table_2
FOR INSERT, UPDATE 
AS BEGIN
  UPDATE dbo.Table_2 SET dbo.Table_2.memberID = 10000
  FROM INSERTED
  WHERE inserted.id = Table_2.id 
    AND dbo.Table_2.memberID > 10000
END



回答2:


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:

ALTER TABLE dbo.mytable ADD CONSTRAINT CK_HAPPINESS_MAX CHECK (PokemonHappiness <= 10000)

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 a CHECK constraint as a hard bound to what can be inserted (just in case of unmoderated input values).




回答3:


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:

UPDATE dbo.MyTable 
SET PokemonHappiness = 
       ( CASE 
           WHEN (PokemonHappiness + 50) > 10000 THEN 10000
           ELSE (PokemonHappiness + 50) 
         END
       )



回答4:


You can achieve that with this

update mytable set PokemonHappiness=(CASE WHEN (PokemonHappiness+50) > 10000 
                                      THEN 10000 ELSE PokemonHappiness+50 END)

OR with two queries

update mytable set PokemonHappiness=PokemonHappiness+50 

update mytable set PokemonHappiness=10000 where PokemonHappiness > 10000


来源:https://stackoverflow.com/questions/12868213/is-it-possible-to-set-a-maximum-value-for-a-column-in-sql-server-2008-r2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!