Limit SQL Server column to a list of possible values

自闭症网瘾萝莉.ら 提交于 2019-12-20 10:20:50

问题


How do I put a constraint on a column so that it can only contain the following values? What do you call this type of constraint?

Allowed values: "yes", "no" or "maybe"
Column Data Type: nvarchar(5)
DBMS: SQL Server 2008

回答1:


you can use a CHECK constraint

ALTER TABLE <table>
ADD CONSTRAINT chk_val CHECK (col in ('yes','no','maybe'))

MSDN link




回答2:


Yes, check a constraint is it what you need. You can declare check constraint at the table declaration:

CREATE TABLE test(
    _id BIGINT PRIMARY KEY NOT NULL,
    decision NVARCHAR(5),
    CHECK (decision in ('yes','no','maybe'))
);



回答3:


Using enumeration table is a way to go.



来源:https://stackoverflow.com/questions/11981868/limit-sql-server-column-to-a-list-of-possible-values

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