简体   繁体   中英

Windowed functions do not support constants as ORDER BY clause expressions in SQL Server TempTable

This is my dynamic SQL query:

SET @SQL = 'SELECT * FROM 
                (SELECT *, ROW_NUMBER() OVER(ORDER BY '+ @sortBy +') AS rowNumber FROM #temp) A 
            WHERE A.rowNumber BETWEEN ' + CONVERT(varchar(9),
(@startIndex -1) * @PageSize + 1) + ' AND ' + CONVERT(varchar(9), 
(((@startIndex -1) * @PageSize + 1) + @PageSize) - 1)+''

print(@SQL)
exec(@SQL)

And this is the output of the PRINT command:

SELECT * 
FROM
   (SELECT *, ROW_NUMBER() OVER(ORDER BY Typename) AS rowNumber       
    FROM #temp) A 
WHERE A.rowNumber BETWEEN 1 AND 5 

where Typename is the @sortBy parameter value.

But I get this error:

Windowed functions do not support constants as ORDER BY clause expressions.

This may not the solution, but if it helps..

Windowed functions do not support constants as ORDER BY clause expressions.

This error normally observed when you try to have a constant value in ORDER BY clause of a windowed function

like ROW_NUMBER() OVER(ORDER BY 'const_val')

建议您在字符串串联中使用QUOTENAME(@sortBy),这将确保局部变量的内容作为列名有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM