0
我正在尝试为我的一个小项目创建数据库模式,并且遇到了一些障碍。我想要一个设置表来存储我的不同设置。我的问题是设置可以有不同的数据类型:int,varchar,bool,datetime。可以具有不同数据类型的设置类型表的数据库模式
最简单的解决方案是使所有的varchar,但我想问是否有其他设计方案可以采取。
我正在尝试为我的一个小项目创建数据库模式,并且遇到了一些障碍。我想要一个设置表来存储我的不同设置。我的问题是设置可以有不同的数据类型:int,varchar,bool,datetime。可以具有不同数据类型的设置类型表的数据库模式
最简单的解决方案是使所有的varchar,但我想问是否有其他设计方案可以采取。
如果你想在数据库中存储适当类型的数据,这样数据不会被破坏,特别是敏感的东西,如小数点,这可能会导致问题。
我在过去所做的是创建一个表,其中包含设置名称,数据类型以及每个相关类型的值列。然后在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')
至于写入数据,你可以做到这一点与存储过程或在应用程序代码。
你考虑过sql_variant吗? –
@DanGuzman:我希望能够将它们存储在它们的实际数据类型中,即使这意味着要添加更多的表。 –
你可以有一个XML列;这将允许在将来进行简单的更改,以添加不同数据类型的不同设置,或者存储某些列的某些设置值以及其他列的其他设置值。 –