我認爲的一個選擇是使用KVP表來存儲動態「列」(如Mitch首先提到的那樣),將產品表與基於產品ID的KVP表結合起來,然後轉動結果以獲得所有結果結果集中的動態列。
編輯:沿着這些路線的東西:
準備:
create table Product(ProductID nvarchar(50))
insert Product values('Product1')
insert Product values('Product2')
insert Product values('Product3')
create table ProductKVP(ProductID nvarchar(50), [Key] nvarchar(50), [Value] nvarchar(255))
insert ProductKVP values('Product1', 'Key2', 'Value12')
insert ProductKVP values('Product2', 'Key1', 'Value21')
insert ProductKVP values('Product2', 'Key2', 'Value22')
insert ProductKVP values('Product2', 'Key3', 'Value23')
insert ProductKVP values('Product3', 'Key4', 'Value34')
檢索:
declare @forClause nvarchar(max),
@sql nvarchar(max)
select @forClause = isnull(@forClause + ',', '') + '[' + [Key] + ']' from (
select distinct [Key] from ProductKVP /* WHERE CLAUSE */
) t
set @forClause = 'for [Key] in (' + @forClause + ')'
set @sql = '
select * from (
select
ProductID, [Key], [Value]
from (
select k.* from
Product p
inner join ProductKVP k on (p.ProductID = k.ProductID)
/* WHERE CLAUSE */
) sq
) t pivot (
max([Value])' +
@forClause + '
) pvt'
exec(@sql)
結果:
ProductID Key1 Key2 Key3 Key4
----------- --------- --------- --------- -------
Product1 NULL Value12 NULL NULL
Product2 Value21 Value22 Value23 NULL
Product3 NULL NULL NULL Value34
Yeap-這是一個關於KV對的SO帖子 - http://stackoverflow.com/questions/126271/key-value-pairs-in-relational-database – RichardOD 2009-09-09 15:20:43