In my database I have a few products. Those products have an unknowningly amount of parameters/fields stored as a name and value in a separate table.
http://sqlfiddle.com/#!18/f3b3e
CREATE TABLE Products
([ProductId] varchar(50), [Name] varchar(50))
;
INSERT INTO Products
([ProductId], [Name])
VALUES
('PROD1', 'Product 1'),
('PROD2', 'Product 2'),
('PROD3', 'Product 3')
;
CREATE TABLE ProductFields
([ProductId] varchar(50), [Name] varchar(50), [Value] varchar(50))
;
INSERT INTO ProductFields
([ProductId], [Name], [Value])
VALUES
('PROD1', 'Color', 'Red'),
('PROD1', 'Size', '2'),
('PROD1', 'Weight', '50'),
('PROD2', 'Color', 'Blue'),
('PROD2', 'Size', '1'),
('PROD2', 'Weight', '15'),
('PROD3', 'Color', 'Yellow'),
('PROD3', 'Size', '3'),
('PROD3', 'Weight', '10')
;
If I have 3 products, I want my output to contain 3 rows that looks like this:
ProductId Name Color Size Weight
----------- ----------- --------- -------- ---------
PROD1 Product 1 Red 2 50
PROD2 Product 2 Blue 1 15
PROD3 Product 3 Yellow 3 10
How do I create a dynamic PIVOT that also has an INNER JOIN against that other table? All values are nice and simply VARCHARs, so that should be quite easy, however, I can't wrap my head around PIVOTs with dynamic values.
This is my go at it:
DECLARE
@cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(pf.Name)
FROM ProductFields pf
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT p.ProductId, p.Name, ' + @cols + ' from
(
SELECT p.ProductId, p.Name FROM Products p
INNER JOIN ProductFields pf
ON pf.ProductId = p.ProductId
) x
pivot
(
Value
for Name in (' + @cols + ')
) pi '
execute(@query)