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?

DECLARE @col VARCHAR(9)
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:

DECLARE @col VARCHAR(9)
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 *

*


1 + 6 =

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>