如何在SQL中存储DropDownList信息

时间:2012-02-08 21:11:26

标签: sql-server database database-design drop-down-menu

我希望在SQL Server中存储多个下拉列表的内容。将它们存储在每个下拉列表中的一个表中,还是放在更大的表中更好?

我的大表将具有如下架构:

CREATE TABLE [dbo].[OptionTable](
    [OptionID] [int] IDENTITY(1,1) NOT NULL,
    [ListName] [varchar](100) NOT NULL,
    [DisplayValue] [varchar](100) NOT NULL,
    [Value] [varchar](100) NULL,
    [OptionOrder] [tinyint] NULL,
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) ON [PRIMARY]

我会通过以下方式获取1个列表的内容:

Select [columns]
From OptionTable
WHERE ListName = 'nameOfList'

那我该怎么决定?我知道它会像这样工作,我不确定这是不是很好的做法?一种方式会更好吗?可读性怎么样?意见表示赞赏。

2 个答案:

答案 0 :(得分:5)

我曾在数据库中工作过一个“超级选项表”,其中包含多个下拉列表的值...它对下拉列表填充有效,但是当我需要将这些值用于其他报告时目的,它变得很痛苦,因为“超级选项表”需要根据我需要的特定选项集进行过滤,最终会出现一些难看的查询。

此外,在路上有条件需要使用其中一个列表跟踪其他值...但是该列需要添加到整个表中,然后是该列中的所有其他选项集对于他们不关心的列,表格只有一个NULL ...

正因为如此,我建议如果你处理完全不同的数据列表,那些列表将存储在不同的表中。

答案 1 :(得分:2)

快捷方便:

CREATE TABLE [dbo].[Lists](
    [ListId] [int] IDENTITY(1,1) NOT NULL,
    [ListName] [varchar](100) NOT NULL,
    --these could be associated with lists or options, wasn't specified
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[Options](
    [OptionId] [int] IDENTITY(1,1) NOT NULL,
    [ListId] [int] NOT NULL,
    [DisplayValue] [varchar](100) NOT NULL,
    [Value] [varchar](100) NULL,
    [OptionOrder] [tinyint] NULL,
    --these could be associated with lists or options, wasn't specified
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) ON [PRIMARY]

使用

获取内容
select Options.* --or a subset
from Options as o
join Lists as l
    on l.ListId=o.ListId and l.ListName = 'nameOfList'
order by o.OptionOrder

(可能:取决于您的数据)更优化(特别是如果一个选项出现在多个列表中)

CREATE TABLE [dbo].[Lists](
    [ListId] [int] IDENTITY(1,1) NOT NULL,
    [ListName] [varchar](100) NOT NULL,
    --these could be associated with lists or options, wasn't specified
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[Options](
    [OptionId] [int] IDENTITY(1,1) NOT NULL,
    [DisplayValue] [varchar](100) NOT NULL,
    [Value] [varchar](100) NULL,
    --these could be associated with lists or options, wasn't specified
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ListOptions](
    [OptionId] [int] NOT NULL,
    [ListId] [int] NOT NULL,
    [OptionOrder] [tinyint] NULL,
    --these could be associated with lists or options, wasn't specified
    [AssociatedDept] [int] NULL,
    [Other2] [nchar](10) NULL,
    [Other3] [nchar](10) NULL
) 

使用

获取内容
select Options.* --or a subset
from Options as o
join ListOptions as lo
    on lo.OptionId=o.OptionId
join Lists as l
    on l.ListId=lo.ListId and l.ListName = 'nameOfList'
order by lo.OptionOrder

在其中一个上,您需要索引外键列。