How can I ORDER BY different fields based on a variable in SQL Server?

A. There are three ways :-

1. Build up the whole select statement including the order by into a string and then use the EXEC (@str) command where @str contains the SQL to be run.

2. As above, but using sp_executesql. See exec.txt in the faq for more details on these two.

3. If all the fields are of the same datatype then you can use the CASE statement.

declare @var int
select @var=1
select * from tbl
order by CASE
WHEN @var=1 THEN field1
WHEN @var=2 THEN field2
WHEN @var=3 THEN field3
ELSE field4

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.