Enumerated types in SQL Server 2008?

若如初见. 提交于 2019-12-19 17:57:31

问题


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.


回答1:


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.




回答2:


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'))
)



回答3:


The only way that I've seen this done is by using a UDF to evaluate whether or not the enum's string representation is valid. It's slow, it's painful, and usually not worth it, but at least you have a way to fail loudly instead of silently.

And remember, you can't RAISERROR in a UDF so you have to cause an intentially cause an error, and log separately.

Ultimately, at the moment, the 'perfect' solution to the problem would be to approach from the other side -- you can achieve this mentality with a code-first ORMs, which would allow you to use native enums in your code, and the corresponding SQL lookups will be created properly in migration.

Here's to hoping we get enums soon, we're feeling a little left out.



来源:https://stackoverflow.com/questions/2373421/enumerated-types-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!