SQL Server add a column constraint to limit data to -1 to 1

淺唱寂寞╮ 提交于 2019-12-04 10:29:39
gbn
CREATE TABLE foo (
    bar int NOT NULL CONSTRAINT CK_foo_bar CHECK (bar IN (-1, 0, 1))
)

or

ALTER TABLE foo WITH CHECK ADD --added WITH CHECK
   CONSTRAINT CK_foo_bar CHECK (bar IN (-1, 0, 1)) --not needed "FOR bar"

Edit: thoughts...

  • why constrain a decimal? Can you change it to smallint or int?
  • what about NULLs? You may need to change my code around to do exactly what you want
create table (
    x integer check (x = -1 or x = 0 or x = 1), 
    y integer
);


insert test values(5,5)
insert test values(-1, 5)
insert test values(0, 5)
insert test values(1, 5)

alter table test with nocheck add check(y = -1 or y = 0 or y = 1);
-- with no check prevents errors for illegal values already in the table
insert test values(-1, 1)
insert test values(0, -1)
insert test values(1, 0)

select * from test

You are probably looking for CHECK Constraints

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