SQL Server 2005 Error - “”MAX“ is not a recognized table hints option”

有些话、适合烂在心里 提交于 2019-12-12 18:58:59

问题


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.


回答1:


You are missing a space between PivotData and PIVOT.

    SET @query = @query  + 
    ' PIVOT (MAX(VALUE) FOR [NAME] IN (' + @columns + ')) AS p' 
//   ^--- HERE

As the result, the SQL parser interprets PivotDataPIVOT as a single identifier, resulting in a syntax error later on.



来源:https://stackoverflow.com/questions/13416260/sql-server-2005-error-max-is-not-a-recognized-table-hints-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!