可以具有不同数据类型的设置类型表的数据库模式

时间:2017-02-01 02:44:48

标签: sql-server database

我目前正在尝试为我的一个小项目创建数据库架构,而且我遇到了一些障碍。我想要一个设置表来存储我的不同设置。我的问题是设置可以有不同的数据类型:int,varchar,bool,datetime。

最简单的解决方案是制作所有varchar,但我想问一下我是否还有其他设计选择。

1 个答案:

答案 0 :(得分:0)

您想要在数据库中存储具有相应类型的数据是正确的,这样数据就不会被破坏,特别是像i18n可能导致问题的小数字这样的敏感内容。

我过去所做的是创建一个包含每个相关类型的设置名称,数据类型和值列的表。然后在UDF或应用程序代码中,使用正确的列动态获取/设置它。

例如:

create table settings (
    id            int identity(1,1) primary key,
    name          sysname not null,
    value_type    varchar(20) not null,

    int_value     int           not null default 0,
    decimal_value decimal(10,2) not null default 0,
    bool_value    bit           not null default 0,
    string_value  nvarchar(max) null
)
create unique index IX_settings on settings (name);
go

create function dbo.GetSetting(@name sysname) returns sql_variant as
begin;
    declare @retval sql_variant;
    select
        @retval = case value_type
            when 'int'     then int_value
            when 'bool'    then bool_value
            when 'string'  then string_value
            when 'decimal' then decimal_value
        end
    from settings
    where name = @name;

    return @retval;
end;
go

insert into settings (name, value_type, int_value) values ('limit', 'int', 10);
insert into settings (name, value_type, bool_value) values ('enabled', 'bool', 1);
insert into settings (name, value_type, decimal_value) values ('rate', 'decimal', 9884.45);
select dbo.GetSetting('limit'), dbo.GetSetting('enabled'), dbo.GetSetting('rate')

至于编写数据,您可以使用存储过程或应用程序代码执行此操作。

相关问题