我正在尝试通过SQL服务器引用此链接来实现动态排序 https://dba.stackexchange.com/questions/4104/how-do-you-order-by-a-parameter/4111#4111?newreg=9f2079e714554009886acbd7510eb666
Declare @sortColumn varchar(50) = 'StateName'
Declare @SortOrder Varchar(50) = 'ASC'
SELECT [StateId],[StateName],[IsActive]
FROM [States]
ORDER BY
CASE WHEN @SortOrder = 'ASC' THEN
CASE
WHEN @sortColumn = 'StateId' THEN StateId
WHEN @sortColumn = 'StateName' THEN StateName
END
END ASC
, CASE WHEN @SortOrder = 'DESC' THEN
CASE
WHEN @sortColumn = 'StateId' THEN StateId
WHEN @sortColumn = 'StateName' THEN StateName
END
END DESC
当我通过@sortColumn =' StateId'然后它工作正常,但当我通过' stateName'作为变量然后它会抛出错误 "转换varchar值时转换失败' Abcde'到数据类型int。"
我做错了什么?