简体   繁体   中英

How do I ensure a column contains one of a set of values?

I'm creating a table that looks something like this.

CREATE TABLE packages
(
  productCode char(2)
  , name nvarchar(100) 
  , ...
)

How do I make sure the productCode is always one of two values XJ or XD ?

ALTER TABLE packages
ADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))

使其成为查找表的外键 ,或添加检查约束来强制执行它。

CREATE TABLE packages
(
  productCode char(2)
  , name nvarchar(100) 
  , ...
  ,CONSTRAINT productCode CHECK (productCode in ('XJ','XD') )
)

In this case it sounds like the valueset for ProductCode is pretty limited and that you don't expects it to grow in a foreseeable future, so I tend to agree with checkconstraint answers. However in most cases I would implement the foreign key solution as suggested by Mr. Grant as my customers has a nasty habit of changing their mind ( and the requirements as well ) about once a day. In that situation it is my expirence that the FK version is easier to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM