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

Neil Pike

December 23, 1999

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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
END

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like