Using variable in order by clause in MS SQL Server

Clearly, SQL Server doesn’t like variables in the ORDER BY clause. Well, we can just use dynamic SQL, right?

SET @col = 'FirstName'
EXEC('SELECT * FROM Table_Name ORDER BY ' + @col)

But dynamic SQL is not a very good solution. So below is another way to use variable in  ORDER BY clause:

SET @col = 'FirstName'
IF @col = 'FirstName'
SELECT * FROM Table_Name ORDER BY FirstName
IF @col = 'Email'
SELECT * FROM Table_Name  ORDER BY Email

Comments & Responses

Leave a Reply

Your email address will not be published. Required fields are marked *


9 − = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>