您的属性的实际值在哪里?您当前表唯一可以使用的是NVARCHAR,因为“datetime”不是有效的datetime值,“int”不是有效的int值等等。
假设同一个表包含属性的值,那么另一种方法是使用sql_variant:
drop table #t
go
create table #t (
AttrID int primary key,
AttrName nvarchar(256) not null,
AttrValue sql_variant not null,
AttrDataType as sql_variant_property(AttrValue, 'BaseType')
)
go
insert into #t (AttrID, AttrName, AttrValue) select 1, N'Test integer', cast(1 as int)
insert into #t (AttrID, AttrName, AttrValue) select 2, N'Test datetime', getdate()
insert into #t (AttrID, AttrName, AttrValue) select 3, N'Test decimal', cast(1.0 as decimal(2,1))
go
select * from #t
但是sql_variant 有一些很大的缺点:它不能存储所有的数据类型,不是所有的工具和库都支持它,它需要在各处进行额外的编码才能将其转换为“真实”数据类型等。