Wednesday, January 9, 2008

Pivot Tables with Dynamic Columns

Pivot Tables with Dynamic Columns

DECLARE @Cols VARCHAR(2000)SELECT @Cols = COALESCE(@Cols + ',[' + AttributeName + ']', '[' + AttributeName + ']')
FROM Attributes
ORDER BY AttributeName

SET @Query = N'SELECT Documents.*, ' + @Cols + ' FROM
(SELECT DocumentValues.DocumentID, DocumentValues.Value, Attributes.AttributeName FROM Attributes INNER JOIN DocumentValues ON Attributes.AttributeID = DocumentValues.AttributeID) p
PIVOT (
MAX([Value])
FOR AttributeName IN (' + @Cols + ')
) AS DocumentValues INNER JOIN
Documents ON DocumentValues.DocumentID = Documents.DocumentID'