Pivot Tables with Dynamic Columns
SET @Query = N'SELECT Documents.*, ' + @Cols + ' FROMDECLARE @Cols VARCHAR(2000)
SELECT @Cols = COALESCE(@Cols + ',[' + AttributeName + ']', '[' + AttributeName + ']')
FROM Attributes
ORDER BY AttributeName
(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'