I am trying to use dynamic SQL to do a pivot on a table for which I need to dynamically generate the column names. My code is:
DECLARE @columns varchar(max)
DECLARE @query varchar(max)
SELECT @columns = COALESCE(@columns + ',[' + cast([Name] as varchar(max)) + ']',
'[' + cast([Name] as varchar(max))+ ']')
FROM dbo.Temp2
SET @query = 'SELECT * FROM dbo.Temp2 AS PivotData'
SET @query = @query +
'PIVOT (MAX(VALUE) FOR [NAME] IN (' + @columns + ')) AS p'
EXEC (@query)
My @columns function seems to work (though I can only 'print' 8000 characters to verify), and I have read that it is acceptable to do a MAX or MIN function on non-numeric varchars in SQL 2005, but when I run the query in its complete form I get the error message:
Msg 321, Level 15, State 1, Line 1
"MAX" is not a recognized table hints option. If it is intended as a parameter to a table-valued function, ensure that your database compatibility mode is set to 90.
I have checked the compatibility level and it is set to 90. Can anyone offer any suggestion for how to get past this?
Many thanks in advance.