Один из вариантов, который я считаю, состоит в том, чтобы использовать таблицу KVP для хранения динамических «столбцов» (как впервые упомянул Митч), объединить таблицу продуктов с таблицей 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