SQL Server 相当于 MySQL 枚举数据类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1434298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:39:09  来源:igfitidea点击:

SQL Server equivalent to MySQL enum data type?

sqlsql-servertsqlsql-server-2008types

提问by Patrick

Does SQL Server 2008 have a a data-type like MySQL's enum?

SQL Server 2008 有像 MySQL 那样的数据类型enum吗?

回答by chaos

It doesn't. There's a vague equivalent:

它没有。有一个模糊的等价物:

mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))

回答by user1431422

The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.

我在此找到的最佳解决方案是创建一个以可能的值作为主键的查找表,并为查找表创建一个外键。

回答by Jony Adamit

IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4

恕我直言,查找表是要走的路,具有参照完整性。但前提是您通过以下示例避免“邪恶的魔法数字”: 使用 T4 从数据库查找表生成枚举

Have Fun!

玩得开心!

回答by Dimitrios Staikos

CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 0
END

GO

CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 1
END

-- etc...

Where performance matters, still use the hard values.

在性能很重要的地方,仍然使用硬值。

回答by user_v

Found this interesting approach when I wanted to implement enums in SQL Server.

当我想在 SQL Server 中实现枚举时发现了这个有趣的方法。

The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.

考虑到您的所有数据库枚举需求都可以通过 2 个中央表来满足,链接中下面提到的方法非常引人注目。

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/