Friday, October 27, 2006

PIVOT dynamic column list

There was an intersting question posted on the .NET forum yday. it was about dynamically changing column list. In PIVOT you have to specify the output column list manually?
is it a bug ??

I found to achive it by doing hours of trying ....

DECLARE @colList VARCHAR(1024)

SELECT @colList = COALESCE(@colList + ',', '') + Subject FROM
(
SELECT DISTINCT '[' + Subject + ']' AS Subject
FROM StudentMarks
) AS StudentMarksColList

--get the column in the array format [maths], [science] ect ..
SELECT @colList


EXEC('SELECT * FROM StudentMarks
PIVOT
(
SUM(Marks)
FOR Subject
IN ('+ @colList +')
)AS p')

No comments: