Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SQL Server 2005 have an equivalent to MySql's ENUM data type?

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.

like image 977
matt.mercieca Avatar asked Nov 04 '08 18:11

matt.mercieca


People also ask

Does SQL Server have ENUM?

Answers. In sql server there is no datatype like mySQL enum.

Is ENUM a string type in SQL?

An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.

How does ENUM work in SQL?

ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a') . The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.

What is ENUM data type in database?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.


2 Answers

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'
like image 136
Nikki9696 Avatar answered Oct 02 '22 13:10

Nikki9696


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.

like image 39
Bill Karwin Avatar answered Oct 02 '22 14:10

Bill Karwin