I’m trying to do a dynamic order by on pubs database and getting the following error
when I try to use @sort_order = 2
Msg 245, Level 16, State 1, Line 6
Conversion failed when converting the nvarchar value ‘Pavlova’ to data type int.
SELECT * FROM Paging
WHERE seq > (@page_nbr - 1) * @page_size
AND seq <= @page_nbr * @page_size
ORDER BY CASE
WHEN @sort_order = 1 THEN ProductID
WHEN @sort_order = 2 THEN ProductName
ELSE CategoryID
END
ProductID,ProductName, andCategoryIDare of different types. All cases of CASE need to evaluate to the same type.Check out this thread for other alternatives: https://stackoverflow.com/a/751659/1373170
Both the accepted answer (multiple case statements) and the
ROW_NUMBER()approach seem valid.