tags:

views:

129

answers:

4

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

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

I want to make sure the productCode is always one of two values: XJ or XD. How do I do that?

+10  A: 
ALTER TABLE packages
ADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))
David B
I would suggest using a lookup table for future expansion reasons. Inserting another row into a table is a lot easier than figuring out how to redo the constraint.
Jon Grant
Yes, I'm invoking YAGNI in this case. :-)
Patrick McElhaney
Does this work in Oracle, MySQL, etc? I'm using MS SQL Server 2000, but if the solution is pretty standard, it would make sense to note that and remove the sqlserver tag.
Patrick McElhaney
Oracle, yes. Mysql - I think not. Mysql seems to want to place a constraint on the column instead of checking the validity of a row.
David B
MySQL does not support CHECK constraints. They can do something similar with their proprietary ENUM data type.
Bill Karwin
+8  A: 

Either make it a foreign key to a lookup table, or add a check constraint to enforce it.

Jon Grant
+3  A: 
CREATE TABLE packages
(
  productCode char(2)
  , name nvarchar(100) 
  , ...
  ,CONSTRAINT productCode CHECK (productCode in ('XJ','XD') )
)
TrickyNixon
Shouldn't the first "productCode" be the name of the constraint instead of the name of the column?
Patrick McElhaney
It is -- of course you can name it anything but if I place a check constraint on a single column, I usually just use the column name.
TrickyNixon
Cool. I had always assumed that a constraint can't have the same name as a column in the same table.
Patrick McElhaney
+1  A: 

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.

Kasper