I need a stored procedure which will allow me to return sorted results based on two input parameters: @sortColumnName and @sortDirection. I wrote the following stored procedure, but when I run it, I am getting this error: "Invalid column name 'LastPayCheckDate'."
SELECT Name, SUM(Pay), MAX(PayCheckDate) as LastPayCheckDate
FROM Employee
GROUP BY Name
ORDER BY
CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'ASC'
THEN [LastPayCheckDate] END ASC,
CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'DESC'
THEN [LastPayCheckDate] END DESC
What is going on? I suppose that t-sql runs the case statement before the select... Am I right? How can I work around this issue?
Thanks for the help!