窗口函数不支持常量作为 SQL Server TempTable 中的 ORDER BY 子句表达式

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

这是我的动态 SQL 查询:

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)

这是 PRINT 命令的输出:

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

其中 Typename@sortBy 参数值。

但是我得到这个错误:

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

这可能不是解决方案,但如果有帮助...

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

当您尝试在 ORDER BY clause of a windowed function

中设置 constant value 时通常会出现此错误

喜欢ROW_NUMBER() OVER(ORDER BY 'const_val')

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