Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerated types in SQL Server 2008?

Is there some kind of mechanism in SQL Server to allow Enumerated type like functionality?

For example, if I have a column Called "UpdateStatus" it usually gets setup with single letter values like so:

  1. D
  2. X
  3. U
  4. I

This could equate to a lot of things. That leads to confusion. The alternative is to have it be a string column like this:

  1. Downloaded
  2. Deleted
  3. Updated
  4. Initialized

But that has its own problems. Eventually someone is going to write something like this: where UpdateStatus = 'Initalized' (spelled wrong). Plus I hear that keying off of strings is not all that performant.

So, is there any kind of enumerated type for SQL Server that can help out with this? Basically I am looking for compile time checking that a value being compared (ie "Initialized") is part of a list of values.

I am using SQL Server 2008.

like image 429
Vaccano Avatar asked Mar 03 '10 17:03

Vaccano


2 Answers

Why not have lookup table that contains the code and description. Creating a foreign key to this lookup table will result in only valid codes being used.

like image 98
Philip Fourie Avatar answered Sep 23 '22 02:09

Philip Fourie


Besides lookup tables (FKs), in simple cases, you can use check constraints:

CREATE TABLE my_table ( 
    UpdateStatus VARCHAR2(11) 
      CHECK( UpdateStatus IN ('Downloaded', 'Deleted', 'Updated', 'Initialized'))
)
like image 29
Alexander Malakhov Avatar answered Sep 21 '22 02:09

Alexander Malakhov