views:

2126

answers:

2

I'm working on a project and I want to store some easily enumerated information in a table. MySql's enum data type does exactly what I want: http://dev.mysql.com/doc/refman/5.0/en/enum.html . Is there an equivalent in SQL Server 2005?

I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions. Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.

+6  A: 

Does this work for you?

From http://blechie.com/wtilton/archive/2007/08/24/303.aspx

Create table...

MySQL:

ColumnName enum('upload','open','close','delete','edit','add') default 'open'

SQL Server

ColumnName varchar(10) CHECK(ColumnName in ('upload','open','close','delete','edit','add')) default 'open'

Nikki9696
That works for me. There is one remaining concern: is there an easy way to tell what valid values are for the enum without selecting out the constraint? I understand there may not be and I'll have to make my decision based on that.
matt.mercieca
I'm not sure what you mean by "selecting out" the constraint, but you might be able to wrap the results of this system query into something usable for your needs.select definition from sys.check_constraints where [name]='yourConstraintName'
Nikki9696
For both ENUM and CHECK constraints, you can query system tables and you get a string with the full syntax specifying the list of values. Then you have to parse that to get the list in a usable format. It's pretty inconvenient to query metadata as if it were data.
Bill Karwin
+2  A: 

One characteristic of MySQL's ENUM data type is that it stores only a numeric index into the list of values, not the string itself, on each row. So it's usually more storage-efficient. Also the default behavior when you sort by an ENUM column is to sort by the numeric index, therefore by the order of elements in the ENUM.

Nikki9696 suggests using a VARCHAR column with a CHECK constraint. This satisfies the restriction of values to a certain short list of permitted values, but it doesn't simulate the storage efficiency or the special sort order.

One way to get both behaviors is to declare the column as an integer foreign key into a lookup table, in which you store each permitted string.

Bill Karwin
An even better option that what I posted, I agree.
Nikki9696
Great alternative. Thank you.
Sung Meister