I want to set order by clause dynamically. I have tried it by using case.
But after few cases its not working for me and I am not getting why this is happening. I have tried the following link http://www.sqlteam.com/article/dynamic-order-by this is working only for 5-6 cases after that I am getting errors of conversion.
ORDER BY CASE WHEN @OrderBY = 1 THEN Pla_BattingAverage
WHEN @OrderBY = 2 THEN Pla_HomeRuns
WHEN @OrderBY = 3 THEN Pla_RBIs
WHEN @OrderBY = 4 THEN Pla_StolenBases
END DESC
You can’t for example mix strings and integers in the results of a case expression.
You could try something like this instead:
Note that this will be slow as an index cannot be used. Generating the query dynamically could give better performance.