Order By parameter in a stored procedure using multiple columns
Posted on 2014-02-26
I'm writing a stored procedure that uses a parameter for the order by clause in a select statement.
The order by has to use single or multiple columns. For example using the adventureWorks2008 database and a query like.
SELECT FirstName , MiddleName , LastName
ORDER BY FirstName , MiddleName , LastName ASC
But in the stored procedure I want to replace the order by clause with a passed in parameter @OrderBy
@OrderBy can be any combination of the columns.
Such as @OrderBy = 'FirstName, MiddleName, LastName' ASC
or @OrderBy = 'LastName, FirstName' DESC
or @OrderBy = 'LastName' ASC
I can get it working with a single column in the passed in order by clause but not with multiple columns. How do I do that?