Enumerated types in SQL Server 2008?

久未见 提交于 2019-12-01 17:25:50

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.

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

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.

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