问:有什么方法可以在“标准SQL”中实现自文档枚举?

   EXAMPLE:
   Column: PlayMode
   Legal values: 0=Quiet, 1=League Practice, 2=League Play, 3=Open Play, 4=Cross Play


我一直做的只是将字段定义为“ char(1)”或“ int”,然后将助记符(“联盟实践”)定义为代码中的注释。

有更好的建议吗?

我绝对希望使用标准SQL,因此数据库类型(mySql,MSSQL,Oracle等)应该无关紧要。我也希望使用任何应用程序语言(C,C#,Java等),因此编程语言也无关紧要。

非常感谢您!

PS:
据我了解,使用第二个表-将代码映射到描述,例如“表播放模式(char(1)id,varchar(10)名称)”-非常昂贵。这一定正确吗?

最佳答案

通常的方法是使用静态查找表,有时也称为“域表”(因为其目的是限制列变量的域)。

取决于您如何使任何枚举等基础值与数据库中的值保持同步(您可以编写代码生成器以从域表中生成枚举,当域表中的某些内容发生更改时,该域表将被调用)

这是一个例子:

--
-- the domain table
--
create table dbo.play_mode
(
  id          int         not null primary key clustered ,
  description varchar(32) not null unique nonclustered   ,
)

insert dbo.play_mode values ( 0 , "Quiet"          )
insert dbo.play_mode values ( 1 , "LeaguePractice" )
insert dbo.play_mode values ( 2 , "LeaguePlay"     )
insert dbo.play_mode values ( 3 , "OpenPlay"       )
insert dbo.play_mode values ( 4 , "CrossPlay"      )

--
-- A table referencing the domain table. The column playmode_id is constrained to
-- on of the values contained in the domain table playmode.
--
create table dbo.game
(
  id          int not null primary key clustered ,
  team1_id    int not null foreign key references dbo.team(      id ) ,
  team2_id    int not null foreign key references dbo.team(      id ) ,
  playmode_id int not null foreign key references dbo.play_mode( id ) ,
)
go


出于“经济”的原因,有些人可能建议对所有此类代码使用单一的万能表,但以我的经验,这最终会导致混乱。最佳做法是为每个离散值集使用一个小表。

10-07 19:09
查看更多